Hidden Uploading file - java

I have one source for upload file from SDCard with have path and Name of file .
this cod works correctly . now I want to automatic run this code in service ( in background ) . can you help me to combine this cod in service ???
this code is for upload file by path and name of file... :
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+uploadFilePath + "" + uploadFileName);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"
+uploadFilePath + "" + uploadFileName);
}
});
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// 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("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);
// 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 (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+uploadFileName;
messageText.setText(msg);
Toast.makeText(MainActivity.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(MainActivity.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(MainActivity.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("UploadException", "Exception : "
+ e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}

It look like you need to update the content on server side; to do so you can implement sync adapter framework. It will trigger the upload or download for you at per the scheduled task.
check this for more.

Related

show ProgressBar while file is uploading

I wrote a code in the Android project that uploads a file with a specific name and address to the server. But ProgressBar does not work well and does not show progress and file upload percentage. But the file upload works well and is located on the server. Now I want to show the percentage of progress in the Progress bar when uploading the file to the server to determine how much of the file has been uploaded to the server.
I tried to do this with AsyncTask.
My code ...
private class UploadTask extends AsyncTask<String, Integer, String> {
private final Context context;
public UploadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
wl.acquire(10 * 60 * 1000L /*10 minutes*/);
try {
String fileName = uploadFilePath + uploadFileName;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(uploadFilePath + uploadFileName);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+ uploadFilePath + "" + uploadFileName);
getActivity().runOnUiThread(new Runnable() {
#SuppressLint("SetTextI18n")
public void run() {
messageText.setText("Source File not exist :"
+ uploadFilePath + "" + uploadFileName);
}
});
Sneaker.with(getActivity())
.setTitle("Error !")
.setMessage("Source File not exist")
.sneakError();
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
// URL url = new URL(upLoadServerUri);
URL url = new URL(sUrl[0]);
// 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("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
String name = key_login_userid + ".JM";
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + name + "\"" + 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);
long total = 0;
while (bytesRead > 0) {
total++;
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
publishProgress((int) (bufferSize * 100 / maxBufferSize));
}
// 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("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
messageText.setText("");
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
getActivity().runOnUiThread(new Runnable() {
#SuppressLint("SetTextI18n")
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Sneaker.with(getActivity())
.setTitle("Error !")
.setMessage("MalformedURLException")
.sneakError();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
getActivity().runOnUiThread(new Runnable() {
#SuppressLint("SetTextI18n")
public void run() {
messageText.setText("Got Exception : see logcat ");
Sneaker.with(getActivity())
.setTitle("Error !")
.setMessage("Got Exception : see logcat")
.sneakError();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}
dialog.dismiss();
} // End else block
} finally {
wl.release();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
dialog.setIndeterminate(false);
dialog.setMax(100);
dialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
if (result != null) {
Sneaker.with(getActivity())
.setTitle("خطا !")
.setMessage("خطا در ارسال اطلاعات.")
.sneakError();
} else {
Sneaker.with(getActivity())
.setTitle("توجه!")
.setMessage("ارسال اطلاعات کامل شد.")
.sneakSuccess();
}
}
}
You can use this code to show progress bar when using Asynctask
https://www.concretepage.com/android/android-asynctask-example-with-progress-bar

File upload not working android

I have the following file upload function:
public void uploadFile(Context context, File file) {
String urlServer = "https://u-database.000webhostapp.com/recieve_file.php";
if(file.isFile() && file.exists()) {
String fileName = file.getAbsolutePath();
try {
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
Toast toastw = Toast.makeText(context, "Inside TRY", Toast.LENGTH_SHORT);
toastw.show();
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlServer);
// 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("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("textLog", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"textLog\";filename=\""+fileName+"\""+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 (code and message)
int serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Toast toast = Toast.makeText(context, "Uploading", Toast.LENGTH_SHORT);
toast.show();
if(serverResponseCode == 200){
file.delete();
Toast toasto = Toast.makeText(context, "success", Toast.LENGTH_SHORT);
toasto.show();
}
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Toast toast = Toast.makeText(context, "Malformed URL", Toast.LENGTH_SHORT);
toast.show();
} catch (Exception e) {
Toast toast = Toast.makeText(context, "Exception", Toast.LENGTH_SHORT);
toast.show();
}
}
}
Each time it is executed, a toast appears stating Inside TRY and then another appears stating "Exception".
I have been debugging a lot and any kind of help would be really appreciated :)
UPDATE
When I did e.toString and printed it out to a toast, I got: android.os.NetworkOnMainThreadException
The answer is simple then. You should run your network calls on a background thread. You need to extend AsyncTask and move your code into it. Something like:
private class InitTask extends AsyncTask<Void, Void, Void>{
protected Void doInBackground(Void... p){
// Call upload file code here
}
}

How to send image and data on jsp server from android app

here is my code that's not working fine, It only post the image on server but i want to post the ID of the image.
I use conn.setRequestProperty("ENID", "76") for sending the id of the image but fails. ENID is the parameter that is used in api.
{
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 20 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :" + filepath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :" + filepath);
}
});
return 0;
} else {
try {
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
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("ENID", "76");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", "File Name is: " + 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);
// 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 (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200) {
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.";
messageText.setText(msg);
Toast.makeText(UpLoadImage.this,
"File Upload Complete.", Toast.LENGTH_SHORT)
.show();
}
});
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText
.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UpLoadImage.this,
"MalformedURLException", Toast.LENGTH_SHORT)
.show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UpLoadImage.this,
"Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
}
}

Resolving java.lang.outofmemory error causing half of the file to be uploaded to server

I am trying to upload large video files to the server. I wrote a piece of code which works well for the image so I thought I should work it for the video too.
I wrote the below code.
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
//Log.v("ONMESSAGE", "File type is " + filetype + "File name is " + fileName);
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(GcmActivity.this, "File not found", Toast.LENGTH_LONG).show();
}
});
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL("http://example.com/ccs-business/upload.php");
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
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("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);//1
buffer = new byte[bufferSize];//2
bytesRead = fileInputStream.read(buffer, 0, bufferSize); //3
while (bytesRead > 0) { //4
dos.write(buffer, 0, bufferSize);//5
bytesAvailable = fileInputStream.available();//6
bufferSize = Math.min(bytesAvailable, maxBufferSize);//7
bytesRead = fileInputStream.read(buffer, 0, bufferSize);//8
}//9
// 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("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(GcmActivity.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
}
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(GcmActivity.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});
Log.v("ONMESSAGE", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(GcmActivity.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.v("ONMESSAGE", "Exception : "
+ e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
This piece of code gives me java.lang.OutOfMemory error so I followed other's suggestion and added a key to manifest that is largeheap, did not work. so I followed other suggestion and changed the code to below
public int uploadFileVideo(String sourceFileUri) {
String fileName = sourceFileUri;
//Log.v("ONMESSAGE", "File type is " + filetype + "File name is " + fileName);
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(GcmActivity.this, "File not found", Toast.LENGTH_LONG).show();
}
});
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL("http://example.com/ccs-business/upload.php");
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
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_video", 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("Content-Disposition: form-data; name=\"uploaded_video\";filename=\"" + fileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
/* bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize); */
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
byte byt[]=new byte[bufferSize];
fileInputStream.read(byt);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
dos.write(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("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(GcmActivity.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
}
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(GcmActivity.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});
Log.v("ONMESSAGE", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(GcmActivity.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.v("ONMESSAGE", "Exception : "
+ e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
Now files gets uploaded however all file size of 1 MB and that too can not be played.
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
byte byt[]=new byte[bufferSize];
fileInputStream.read(byt);
You are not writing the bytes read into byt out to the outputstream. Removing the first read into byt should fix a problem. But you will come across another problem where a file over 1MB only the first 1MB will be uploaded.
A proper way to copy a stream is to do something similar to
byte[] buf = new byte[ 1024 ];
int read = 0;
while( ( read = in.read( buf ) ) != -1 ) {
out.write( buf, 0, read );
}
avoid buffering the whole POST data in RAM by adding conn.setChunkedStreamingMode(0); after : con.setDoOutput(true);
hope this help :)

Android: File upload/download working on emulator but not device

I have been working on a project that requires files to be uploaded and downloaded to and from the mobile device. The code I have works fine on the emulator (I use genymotion emulator since its faster) but on my personal device, neither feature works. Here is what I use for my upload function:
public int uploadFile(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()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+uploadFilePath + "" + curFileName);
runOnUiThread(new Runnable() {
public void run() {
Log.e("Upload","Source File not exist :"
+uploadFilePath + "" + curFileName);
}
});
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// 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
/********************* Header *****************************************************/
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", sourceFileUri);
/******************** Body *******************************************************/
dos = new DataOutputStream(conn.getOutputStream());
//
// Version data
/////////////////////////////////////////////////////////////
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"version\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(VERSION);
dos.writeBytes(lineEnd);
/////////////////////////////////////////////////////////////
// End Version data
//
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + 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 (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Tossup.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Tossup.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Log.e("Upload","Shit got real");
Toast.makeText(Tossup.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload", "Exception : "
+ e.getMessage(), e);
}
try {
//inStream = new DataInputStream(conn.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((str = br.readLine()) != null) {
Log.d("Debug", "Server Response " + str);
}
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
I have not been able to trace the source of this problem and StackOverflow has been great at helping me with other issues. Any suggestions appreciated! Thanks.
Update: I removed the download code since that was not causing an issue

Categories