Upload files(txt,docs,ppt) to server - android

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????

Related

Add param and video(file) in multiple request by post method in Andriod

I am uploading video from android app.i am able to add only video with this code,but i am giving request with video file,but its not working.i added code with this question,help me out from this.
public int uploadFile(final String sourceFileUri) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String action ="action=videoUpload&id="+pHelper.getuser_id()+"&project_id="+Constants.proj_id+"&site_id="+count_et;
Log.d("bf_encoding",action);
// encode
byte[] data = new byte[0];
try {
data = action.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String value = Base64.encodeToString(data, Base64.DEFAULT);
String twoHyphens = "--";
String boundary = "*****";
String mm = "gokgo8gg4ko4gco4okg4ws4o04k44w0go4k";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
return 0;
} else {
try {
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL("https://rahumanmusic.co.in/ar_site/api/video");
Log.d("WebService", "url=" + url);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
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("Headers","X-API-KEY=gokgo8gwskkog4ko4gco4okgo04k44w0go4k");
// conn.getHeaderFieldDate("X-API-KEY", Long.parseLong(mm));
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
Log.d("valuevalue",value);
conn.setRequestProperty("video_upload", filepathUrl1.getName());
conn.setRequestProperty("value", value);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"video_upload\";filename=\"" + filepathUrl1.getName() + "\"" + 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);
// Responses from the server (result)
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
result += line;
}
}
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.d("ssk", "result" + result);
return serverResponseCode;
} // End else block
}
In above code,converted base 64 string as value not passing in request. i am stuck in this task,help me out guys
Use this
library for multipart requests, i-e image, video or any other data for POST request

Displaying upload progress in progress dialog

I'm uploading a file and want to display a progress dialog to see the upload progress. I already included a horizontal dialog which works incorrectly, because it goes to 100% in 1 second and then it waits (because it's still uploading).
I used the following function for uploading:
private void doFileUpload(String selectedPath){
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 = "";
String urlString = "https://xxxxxxxxxx.com";
try
{
//------------------ CLIENT REQUEST
File f = new File(selectedPath);
FileInputStream fileInputStream = new FileInputStream(f);
//calculate size of file
wholeFilesize = f.length(); //returns the length in Bytes
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
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=\"upfile\";filename=\"" + selectedPath + "\"" + 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)
{
totalReadFilesize+=bytesRead;
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
int progress = (int)((totalReadFilesize*100)/(wholeFilesize));
//Log.i("Progress: ", (int)((totalReadFilesize*100)/(wholeFilesize))+"");
dialog.setProgress(progress);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
//publishProgress(100);
Log.i("Size: ", wholeFilesize+"");
Log.i("Bytes read: ", totalReadFilesize+"");
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Debug","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("Debug","Server Response "+str);
JSONObject jsonObj = new JSONObject(str);
//String status=(String) jsonObj.get("status");
Log.i("TEST", (String) jsonObj.get("message"));
uploadResultMessage = (String) jsonObj.get("message");
Log.i("TEST", uploadResultMessage);
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
} catch (JSONException e) {
e.printStackTrace();
}
}
Does someone know, how should I modify the code to see the real progress of the file, which is being uploaded? I find it strange, because I'm doing the same as the user in his doInBackground() in this thread.

File name not displayed properly

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().

Out of Memory Issue when encode into base64 video file

I am trying to upload the video file into server with convert into base64. But I am getting out of memory exception even size is 2 mb also. How to resolve this issue. Please help me to over out, much appreciate your help.
Here what I am doing
byte [] ba = convertByteArray(videoUri);
String baseimage=Base64.encodeToString(ba, Base64.NO_WRAP);
public byte[] convertByteArray(Uri videoUri){
InputStream iStream=null;
byte[] inputData=null;
try {
iStream = getContentResolver().openInputStream(videoUri);
inputData = getBytes(iStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return inputData;
}
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
Code :
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://your_website.com/upload_audio_test/upload_audio.php";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
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="" + selectedPath + """ + 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
Log.e("Debug","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("Debug","Server Response "+str);
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
Go through the following Sample for more reference :
http://coderzheaven.com/2011/08/uploading-audio-video-or-image-files-from-android-to-server/
For uploading video to server see doFileUpload() method from the above url.

Save and upload more than one image

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); }
}
}

Categories

Resources