I have got an app that can take a picture and deliver me an uri of the given picture.
Next thing, I want to do is send this picture to my webservices.
But, Once i tried that, i got an error that i have had before, which relates to asynctask. So tried to work around it, i have got a HttpManager class which holds the information on how to connect to the webservice, the url itself and where it handles the image uri.
public static String uploadImageToWebservice(String uri, String imageUri) {
HttpURLConnection connection = null;
int responseCode = 0;
String image = "";
try {
URL url = new URL(uri + imageUri);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "text/plain");
/*
* String userpassword = adminUser + ":" + adminPassword; String
* encodedAuthorization = DatatypeConverter
* .printBase64Binary(userpassword.getBytes("UTF-8"));
* connection.setRequestProperty("Authorization", "Basic " +
* encodedAuthorization);
*/
InputStream is = connection.getInputStream();
image = is.toString();
responseCode = connection.getResponseCode();
connection.disconnect();
} catch (IOException e) {
Log.e("URL", "failure response from server >" + e.getMessage()
+ "<");
} finally {
if (connection != null) {
connection.disconnect();
}
}
return image;
}
And this is how i handle this method in my activity.
private void submitImage(String uri) {
HttpAsyncTask at = new HttpAsyncTask();
at.execute(uri);
}
private class HttpAsyncTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String image = HttpManager.uploadImageToWebservice(params[0],
params[1]);
return image;
}
}
And then i call the submitImage method in the oncreate with the Uri of the webservice.
But I'm kind of stuck on where to put in the uri of the image itself for it to be sent as well. I just feel like I'm missing something and i can't figure out where it is. Hopefully its to understand all of this.
Thanks in advance!
use code for uploading image
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;
FileInputStream fileInputStream = new FileInputStream("sourcefile");
URL url = new 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("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("bill", sourceFileUri);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"bill\";filename=\""
+ sourceFileUri + "\"" + 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();
if (serverResponseCode == 200) {
statud = "uploaded";
// messageText.setText(msg);
// Toast.makeText(ctx, "File Upload Complete.",
// Toast.LENGTH_SHORT).show();
// System.out.println("Uploaded successfyuly http: 200");
// recursiveDelete(mDirectory1);
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
php code
<?php
$uploads_dir = './images/';
$tmp_name = $_FILES['bill']['tmp_name'];
$pic_name = $_FILES['bill']['name'];
if (move_uploaded_file($tmp_name, $uploads_dir.$pic_name )) {
echo "uploaded";
}
?>
Related
1 - I tested several applications with bluestacks and all worked fine to download data from internet
2 - I tested my application on real device and worked fine to download data from internet
3 - I tested my application with bluestacks and it does not work to download data from internet
It seems something is wrong with my application code but the point is it still worked with a real device
the code:
public class JSONHttpHandler3 {
private static final String TAG = JSONHttpHandler3.class.getSimpleName();
public JSONHttpHandler3() {
}
public String makeServiceCall3(String FileNewName,String FileDestination,String sourceFileUri) {
int serverResponseCode = 0;
String fileName = FileNewName;
String upLoadServerUri = null;
/************* Php script path ****************/
upLoadServerUri = FileDestination;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 5 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File not exist :" + sourceFileUri);
return "0";
}
else {
try {
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);
int length = fileInputStream.available();
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("BBBuploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder total = new StringBuilder();
String line;
while ((line = in.readLine()) != null)
{
total.append(line).append('\n');
}
Log.d(TAG, "AAAServer Response is: " + total.toString() + ": " + serverResponseCode);
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
if (total.toString().contains("Move successful") == true )
{
Log.e(TAG, "Move To Server successful");
return "Move To Server successful";
}
else
{
Log.e(TAG, "Move To Server Failed");
return "Move To Server Failed";
}
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
return "Move To Server Failed";
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "111Exception: " + e.getMessage());
return "Move To Server Failed";
}
}
} // End else block
Why?
Sorry, the problem is a flag which was previously registered in the real mobile set was checked in the download process and since bluestacks did not have that flag registered, the download process had problem
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
I am trying to make users send some app related files to me. I made a "file request" folder in my drop box page for that. Every time i get this message Error 405 - Method not allowed. Here is my code:
private class UploadFile extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
String sourceFileUri = "/data/com.mostafa.android.roadbump/databases/matab.db";
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;
if (dB.isFile()) {
try {
String upLoadServerUri = "https://www.dropbox.com/request/KJcdVMDyxHvM2So1mJkK";
// open a URL connection to the Server
FileInputStream fileInputStream = new FileInputStream(dB);
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("PUT");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("bill", sourceFileUri);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"bill\";filename=\""
+ sourceFileUri + "\"" + 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);
Log.d("Sasaaa", "Done");
int responseCode = conn.getResponseCode();
String responseMessage = conn.getResponseMessage();
Log.d("Sasaaa", String.valueOf(responseCode));
Log.d("Sasaaa", responseMessage);
// close the streams //
conn.disconnect();
fileInputStream.close();
dos.flush();
dos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
Error 405 - Method not allowed tells me that your request type is not correct. You're trying to execute a PUT request in your server. Please check that again, the server request type might be a POST.
Another thing you need to check is the url or the path you're calling the server method. Incorrect url may result this type of errors.
The last thing you need to check if there's any kind of authentication process before you call the method.
Edit
Dropbox has their own API to upload files to Dropbox server. You might check for them to get this job done easily.
I'm quoting another answer from here for your easy access.
private DropboxAPI<AndroidAuthSession> mDBApi;
File tmpFile = new File(fullPath, "/data/com.mostafa.android.roadbump/databases/matab.db);
FileInputStream fis = new FileInputStream(tmpFile);
try {
DropboxAPI.Entry newEntry = mDBApi.putFileOverwrite("matab.db", fis, tmpFile.length(), null);
} catch (DropboxUnlinkedException e) {
Log.e("DbExampleLog", "User has unlinked.");
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
}
You might take a look at here to get idea of API Key and APP SECRET.
I am uploading a file on server in multipart, It works fine if there is no proxy set on device but on proxy it does not work. See below code -
public int uploadFile(String sourceFileUri, String upLoadServerUri) {
int serverResponseCode = 0;
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()) {
} else {
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
boolean isProxy = true;
ConnectivityManager cm = (ConnectivityManager) AppService
.getAppService().getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null) {
if (!ni.getTypeName().equals("WIFI")) {
isProxy = false;
}
if (isProxy) {
Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,
new InetSocketAddress(
android.net.Proxy.getDefaultHost(),
android.net.Proxy.getDefaultPort()));
conn = (HttpURLConnection) url
.openConnection(proxy);
} else {
conn = (HttpURLConnection) url.openConnection();
}
}
}
// 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(
"Authorization",
"Bearer "
+ CommonFunctions.getAccessToken(AppService
.getAppService()
.getApplicationContext()));
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"userfile\"; filename=\"filename.xml\"\r\n");
dos.writeBytes("Content-Type: text/xml" + lineEnd + 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 || serverResponseCode == 204) {
offlineAnalyticsOperations();
} else {
// for now unless code is restructured
if (NetUtils.isNetworkConnected(AppService.getAppService()
.getApplicationContext())) {
offlineAnalyticsOperations();
}
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.v("msg", ex.getMessage());
} catch (Exception e) {
Log.v("msg", e.getMessage());
}
} // End else block
return serverResponseCode;
}
I don't know the proxy and port and password too. And I can't ask this information to user. How can I achieve that? and why it is not working on proxy. I am using other API's for getting the json response those are not giving me such errors(Those I am getting through httpConnection) and in this file upload I am using url connection. Is that the problem? I have tried with the httpConnection but it was not working on both proxy and non Proxy.
I am poor in networking.So not understanding the problem.
Thanks in advance.
I've ben stuck on this for a while. I have an asynch task that uploads an image to a web server. Works fine.
I'm have a progress bar dialog set up for this. My problem is how to accurately update the progress bar. Everything I try results in it going from 0-100 in one step. It doesn't matter if it takes 5 seconds or 2 minutes. The bar hangs onto 0 then hits 100 after the upload is done.
Here's my doInBackground code. Any help is appreciated.
EDIT: I updated the code below to include the entire AsynchTask
private class UploadImageTask extends AsyncTask<String,Integer,String> {
private Context context;
private String msg = "";
private boolean running = true;
public UploadImageTask(Activity activity) {
this.context = activity;
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMessage("Uploading photo, please wait.");
dialog.setMax(100);
dialog.setCancelable(true);
}
#Override
protected void onPreExecute() {
dialog.show();
dialog.setOnDismissListener(mOnDismissListener);
}
#Override
protected void onPostExecute(String msg){
try {
// prevents crash in rare case where activity finishes before dialog
if (dialog.isShowing()) {
dialog.dismiss();
}
} catch (Exception e) {
}
}
#Override
protected void onProgressUpdate(Integer... progress) {
dialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(String... urls) {
if(running) {
// new file upload
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String exsistingFileName = savedImagePath;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024 * 1024;
String urlString = "https://mysite.com/upload.php";
float currentRating = ratingbar.getRating();
File file = new File(savedImagePath);
int sentBytes = 0;
long fileSize = file.length();
try {
// ------------------ CLIENT REQUEST
// 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=\""
+ exsistingFileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName));
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);
// Update progress dialog
sentBytes += bufferSize;
publishProgress((int)(sentBytes * 100 / fileSize));
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.flush();
dos.close();
fileInputStream.close();
}catch (MalformedURLException e) {
}catch (IOException e) {
}
// ------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
// try to read input stream
// InputStream content = inStream.getContent();
BufferedInputStream bis = new BufferedInputStream(inStream);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
long total = 0;
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
/* Convert the Bytes read to a String. */
String mytext = new String(baf.toByteArray());
final String newtext = mytext.trim();
inStream.close();
} catch (Exception e) {
}
}
return msg;
}
}
This should work !
connection = (HttpURLConnection) url_stripped.openConnection();
connection.setRequestMethod("PUT");
String boundary = "---------------------------boundary";
String tail = "\r\n--" + boundary + "--\r\n";
connection.addRequestProperty("Content-Type", "image/jpeg");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Length", ""
+ file.length());
connection.setDoOutput(true);
String metadataPart = "--"
+ boundary
+ "\r\n"
+ "Content-Disposition: form-data; name=\"metadata\"\r\n\r\n"
+ "" + "\r\n";
String fileHeader1 = "--"
+ boundary
+ "\r\n"
+ "Content-Disposition: form-data; name=\"uploadfile\"; filename=\""
+ fileName + "\"\r\n"
+ "Content-Type: application/octet-stream\r\n"
+ "Content-Transfer-Encoding: binary\r\n";
long fileLength = file.length() + tail.length();
String fileHeader2 = "Content-length: " + fileLength + "\r\n";
String fileHeader = fileHeader1 + fileHeader2 + "\r\n";
String stringData = metadataPart + fileHeader;
long requestLength = stringData.length() + fileLength;
connection.setRequestProperty("Content-length", ""
+ requestLength);
connection.setFixedLengthStreamingMode((int) requestLength);
connection.connect();
DataOutputStream out = new DataOutputStream(
connection.getOutputStream());
out.writeBytes(stringData);
out.flush();
int progress = 0;
int bytesRead = 0;
byte buf[] = new byte[1024];
BufferedInputStream bufInput = new BufferedInputStream(
new FileInputStream(file));
while ((bytesRead = bufInput.read(buf)) != -1) {
// write output
out.write(buf, 0, bytesRead);
out.flush();
progress += bytesRead;
// update progress bar
publishProgress(progress);
}
// Write closing boundary and close stream
out.writeBytes(tail);
out.flush();
out.close();
// Get server response
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Reference : http://delimitry.blogspot.in/2011/08/android-upload-progress.html
You need to do the division on float values and convert the result back to int:
float progress = ((float)sentBytes/(float)fileSize)*100.0f;
publishProgress((int)progress);
You can do like:
try { // open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL("http://10.0.2.2:9090/plugins/myplugin/upload");
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("uploadedfile", filename);
// conn.setFixedLengthStreamingMode(1024);
// conn.setChunkedStreamingMode(1);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ filename + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = (int) sourceFile.length()/200;//suppose you want to write file in 200 chunks
buffer = new byte[bufferSize];
int sentBytes=0;
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
// Update progress dialog
sentBytes += bufferSize;
publishProgress((int)(sentBytes * 100 / bytesAvailable));
bytesAvailable = fileInputStream.available();
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();
// close streams
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
I had the same problem and this helped me. This can help you too.
In your Async task class, write (paste) the following code.
ProgressDialog dialog;
protected void onPreExecute(){
//example of setting up something
dialog = new ProgressDialog(your_activity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
for (int i = 0; i < 20; i++) {
publishProgress(5);
try {
Thread.sleep(88);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
dialog.dismiss();
return null;
}
protected void onProgressUpdate(Integer...progress){
dialog.incrementProgressBy(progress[0]);
}
If error occurs, remove "publishProgress(5);" from the code. Otherwise its good to go.
I spend two days with this example.
And all in this string.
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
Only it helps.