I want to upload an image to web server.For that i have written code,but when ever i upload the file to web server instead of file name i am getting the image path.
COde
protected String sendFile(final Context context, final String url, final String params, String fileName, final File f) {
DataOutputStream dos = null;
int bytesRead = 0, bytesAvailable = 0, bufferSize;
int maxBufferSize = 1024;
byte[] buffer;
String serverResponseMessage = null;
String uploaded_file = fileName;
URL url1 = null;
try {
FileInputStream fileInputStream = new FileInputStream(f);
url1 = new URL(url + "?" + params);
HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file", fileName);
fileName = String.valueOf(f);
//connection.setRequestProperty ("uploaded_file", "sample");
dos = new DataOutputStream(connection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"hello" + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.close();
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
serverResponseMessage = connection.getResponseMessage();
StringBuffer b;
int ch;
InputStream is;
is = connection.getInputStream();
// retrieve the response from server
b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
String response = b.toString();
Log.e("Response", "" + response);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
Log.e("Error message", "" + e);
}
return serverResponseMessage;
}
protected File saveFile(Context context, int value, String name) {
File directory = new File(Environment.getExternalStorageDirectory() + "/pocketDocs/Camera/Gallery/Others");
if (!directory.exists()) {
directory.mkdirs();
}
if (value == 0) {
f = new File(Environment.getExternalStorageDirectory() + "/pocketDocs/Gallery", name);
try {
FileOutputStream out = new FileOutputStream(f);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return f;
}
}
When i use
fileName = String.valueOf(f);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"hello" + fileName + "\"" + lineEnd);
at server side i am getting the file name as the path of image.
And when i don't use
fileName = String.valueOf(f);
i am gettin the proper file name but i am not getting the extension of the image.
Now how can i solve this problem because the peoblem is in this line
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"hello" + fileName + "\"" + lineEnd);
You were using String.valueOf() in a file to get its name, it was returning an empty String, so it was not working.
Instead, you have to get the file name using file.getName().
Related
I am using HttpURLConnection to upload a file to the server but i could not figure out how can i add other parameters to send String data along with file.
This is the code i am using to upload the file.
public String sendFileToServer(String filename, String targetUrl) {
String response = "error";
Log.e("Image filename", filename);
Log.e("url", targetUrl);
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
// DataInputStream inputStream = null;
String pathToOurFile = filename;
String urlServer = targetUrl;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
DateFormat df = new SimpleDateFormat("yyyy_MM_dd_HH:mm:ss");
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(
pathToOurFile));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(1024);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
String connstr = null;
connstr = "Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ pathToOurFile + "\"" + lineEnd;
Log.i("Connstr", connstr);
outputStream.writeBytes(connstr);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Log.e("Image length", bytesAvailable + "");
try {
while (bytesRead > 0) {
try {
outputStream.write(buffer, 0, bufferSize);
} catch (OutOfMemoryError e) {
e.printStackTrace();
response = "outofmemoryerror";
return response;
}
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
} catch (Exception e) {
e.printStackTrace();
response = "error";
return response;
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i("Server Response Code ", "" + serverResponseCode);
Log.i("Server Response Message", serverResponseMessage);
if (serverResponseCode == 200) {
response = "true";
}
String CDate = null;
Date serverTime = new Date(connection.getDate());
try {
CDate = df.format(serverTime);
} catch (Exception e) {
e.printStackTrace();
Log.e("Date Exception", e.getMessage() + " Parse Exception");
}
Log.i("Server Response Time", CDate + "");
filename = CDate
+ filename.substring(filename.lastIndexOf("."),
filename.length());
Log.i("File Name in Server : ", filename);
fileInputStream.close();
outputStream.flush();
outputStream.close();
outputStream = null;
} catch (Exception ex) {
// Exception handling
response = "error";
Log.e("Send file Exception", ex.getMessage() + "");
ex.printStackTrace();
}
return response;
}
I have used Volley previously but it fails to upload when file is large, I have to upload Video files up to 20 MB, so if you have any better solution please let me know.
I am using this code in Service so even if user close the app the uploading should continue.
The following code should work:
outputStream = new DataOutputStream(connection.getOutputStream());
// To send string data
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + stringName + "\""+lineEnd);
outputStream.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(stringValue + lineEnd);
outputStream.flush();
// To send file data
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
For more details: link
I am making a app in which user selects a file and uploads it to the server.If the user selects image from gallery the image is being uploaded properly,but when ever the user selects a file like txt or word file its giving me System out of memory exception.
Code to upload files
protected String sendFile(final Context context, final String url, final String params, String fileName, final File f) {
DataOutputStream dos = null;
int bytesRead = 0, bytesAvailable = 0, bufferSize;
int maxBufferSize = 1024;
byte[] buffer;
String serverResponseMessage = null;
String uploaded_file = fileName;
URL url1 = null;
try {
FileInputStream fileInputStream = new FileInputStream(f);
url1 = new URL(url + "?" + params);
HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file", fileName);
fileName = f.getName();
dos = new DataOutputStream(connection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.close();
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
serverResponseMessage = connection.getResponseMessage();
StringBuffer b;
int ch;
InputStream is;
is = connection.getInputStream();
// retrieve the response from server
b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
response = b.toString();
Log.e("Response", "" + response);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
Log.e("Error message", "" + e);
}
return response;
}
Code to select a file
if (requestCode == 2 && resultCode == getActivity().RESULT_OK) {
strFilePath = data.getData().getPath();
}
Logcat
07-30 12:15:03.069 7829-8085/example.com.pocketdocs E/Upload file response﹕ System.OutOfMemoryException: Out of memory.
at System.Drawing.Image.FromFile(String filename, Boolean useEmbeddedColorManagement)
at Web_Account_UploadFile.Page_Load(Object sender, EventArgs e) in C:\APP\PocketDocs\PocketDocs\PocketDocsWeb\web\Account\UploadFile.aspx.vb:line 3753
ASP Code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim Ret As String = ""
Try
If Request.Files.Count > 0 Then
'Dim Posted_File As HttpPostedFile
'Posted_File = Request.Files.Get(0)
Dim objPocketDocs As New PocketdocsEntities
Dim ListDocID As Decimal = objPocketDocs.ins_doc_details(Request.QueryString("User_ID"), Posted_File.FileName, Path.GetExtension(Posted_File.FileName), Request.QueryString("User_ID"), Request.QueryString("FileTitle").ToString, Request.QueryString("DT")).FirstOrDefault
If Not My.Computer.FileSystem.DirectoryExists(Server.MapPath("\IMSAFE") & "\TripImages") Then
My.Computer.FileSystem.CreateDirectory(Server.MapPath("\IMSAFE") & "\TripImages")
End If
Dim orifilename As String
orifilename = Server.MapPath("/Doc_Files/") & Request.QueryString("User_ID") & "_" & ListDocID & Path.GetExtension(Posted_File.FileName) & Path.GetExtension(Posted_File.FileName)
If File.Exists(orifilename) Then
File.Delete(orifilename)
Why images are being uploded properly but uploading a file gives me error????
I want to upload a mp3 file to a web server and get its response that should be a string but I get 415 error ,HTTP Response is : Cannot process the message because the content type 'multipart/form-data;boundary=*' was not the expected type 'application/soap+xml; charset=utf-8'.: 415, here is my code, why does the server refuse this format?
public static int upLoad2Server(String sourceFileUri) {
String upLoadServerUri = "http://address:port/example/mex";
// String [] string = sourceFileUri;
String fileName = sourceFileUri;
int serverResponseCode = 0;
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.i("Huzza", "Source File Does not exist");
return 0;
}
try { // open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP
// connection to
// the URL
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // create a buffer of
// maximum size
Log.i("Huzza", "Initial .available : " + bytesAvailable);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necessary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("Upload file to server", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
// close streams
Log.i("Upload file to server", fileName + " File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.i("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
}
// this block will give the response of upload link
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
Log.i("Huzza", "RES Message: " + line);
}
rd.close();
} catch (IOException ioex) {
Log.i("Huzza", "error: " + ioex.getMessage(), ioex);
}
return serverResponseCode; // like 200 (Ok)
} // end upLoad2Server
Your code includes this:
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
and the error is staying that it's expecting Content-Type to be this:
application/soap+xml; charset=utf-8
I recommend re-examining why you're setting the content type to something other than the server accepts.
I'm trying to upload more than one image taken from the camera. I call the camera via Intent:
public void TakePicture(int actionCode)
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try
{
photo[0] = createTemporaryFile("spot", ".jpg");
}
catch(Exception e)
{
Log.v("ERROR SD!!", "Can't create file to take picture!");
Toast.makeText(this, "Please check SD card! Image shot is impossible!", 10000);
}
fileUri = Uri.fromFile(photo[0]);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
And then I upload it to a PHP server:
public void UploadImg()
{
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
// String exsistingFileName = "/sdcard/prueba.png"; --> Used for local files!!
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String urlString = "http://myUrl.com/uploadimg.php";
try
{
FileInputStream fileInputStream = new FileInputStream(photo[0].toString());
// Open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + photo[0] +"\"" + lineEnd);
dos.writeBytes(lineEnd);
// Create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// Send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Close streams
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex) { Log.e("MediaPlayer", "error: " + ex.getMessage(), ex); }
catch (IOException ioe) { Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe); }
try {
inStream = new DataInputStream (conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null)
{
System.out.println("Server Response" + str);
}
inStream.close();
}
catch (IOException ioex) { Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex); }
}
I save 3 different images: photo[0], photo[1] and photo[2]. The problem is that when I take, for example, two pictures, it only uploads one of them and with size = 0.
In the code of the UploadImg() I show only the photo[0], but in the 'real' code I use a for loop after the first try so that it upload all of the images taken.
Any idea of what am I doing wrong?
Thank you very much in advance!
I've already solved my problem! I did the following: Instead of saving the photo File, I save the it in a String with the location of the image.
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
for (int u = 0; u <= 2; u++)
{
if (savedImgs[u].equals(""))
{
// Saving important info to be used later
imgs = u + 1;
savedImgs[u] = photo.toString();
break;
}
} ...
And then, when uploading the images to the server, I make a for loop like this:
public void UploadImg()
{
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
// String exsistingFileName = "/sdcard/prueba.png"; --> Used for local files!!
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String urlString = "http://myUrl.com/uploadimg.php";
for (int n = 0; n < imgs; n++)
{
try
{
FileInputStream fileInputStream = new FileInputStream(savedImgs[n]);
// Open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + savedImgs[n] +"\"" + lineEnd);
dos.writeBytes(lineEnd);
// Create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// Send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Close streams
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex) { Log.e("MediaPlayer", "error: " + ex.getMessage(), ex); }
catch (IOException ioe) { Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe); }
try {
inStream = new DataInputStream (conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null)
{
System.out.println("Server Response" + str);
}
inStream.close();
}
catch (IOException ioex) { Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex); }
}
}
I want to upload video on specific server in Android.
Is is possible ?
How I can achieve this ?
Thanks.
Had the same issue some time ago. Here's a code.
public static int upLoad2Server(String sourceFileUri)
{
String upLoadServerUri = "your remote server link";
// String [] string = sourceFileUri;
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.e("Huzza", "Source File Does not exist");
return 0;
}
try { // open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
Log.i("Huzza", "Initial .available : " + bytesAvailable);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("Upload file to server", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
// close streams
Log.i("Upload file to server", fileName + " File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
}
//this block will give the response of upload link
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
Log.i("Huzza", "RES Message: " + line);
}
rd.close();
} catch (IOException ioex) {
Log.e("Huzza", "error: " + ioex.getMessage(), ioex);
}
return serverResponseCode; // like 200 (Ok)
} // end upLoad2Server