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
}
}
Related
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.
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;
}
}
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 :)
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
I know this is the repeat question.There are many similar questions are there in stack overflow but I am asking this question because I don't understand how I can post some data with Image.
I want to pass first name and last name with the image to the server.
Still now i tried this.
URL connectURL;
connectURL = new URL("some URL");
File sdImageMainDirectory = new File("/sdcard");
String existingFileName = sdImageMainDirectory.toString() +"/image.jpg";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag="3rd";
try
{
HttpURLConnection conn = (HttpURLConnection) connectURL.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);
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"firstname\"" + lineEnd);
dos.writeBytes("Dharmendra");
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"lastname\"" + lineEnd);
dos.writeBytes("Patel");
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName +"\"" + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int 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);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
dos.flush();
dos.close();
}catch (MalformedURLException ex) {
Log.e(Tag, "error: " + ex.getMessage(), ex);
}
catch (IOException ioe) {
Log.e(Tag, "error: " + ioe.getMessage(), ioe);
}
Check this Code for adding additional Values to Uploading Image to Server :
public class Task_TurnoutPost extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(ActivityName.this);
JSONObject object_feed;
// can use UI thread here
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(false);
this.dialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("Your LINK");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("F_Name", new StringBody("F_Name"));
reqEntity.addPart("L_Name",new StringBody("L_NAME"));
try{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
reqEntity.addPart("picture", bab);
}catch(Exception e){
//Log.v("Exception in Image", ""+e);
reqEntity.addPart("picture", new StringBody(""));
}
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
object_feed = new JSONObject(s.toString());
success_response=object_feed.getString("status");
Log.v("Response for POst", s.toString());
} catch (Exception e) {
Log.e("e.getClass().getName()", ""+e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
Where bitmap is your as Bitmap. In addition to it add a library and download it
Check this for you reference
I would actually use the Http headers here to post the key value pairs. Like this
conn.setRequestProperty("firstName", "Stephen");
conn.setRequestProperty("lastName", "glansburg");
Then on your server side you can just look at the http headers for that meta information.