showing progress bar while uploading a video - android

I want to show progress bar while uploading a video from my app to php server.The below will upload the file to the server correctly.But i dont know how to show the progress bar.If anybody knows pls help me.
Here is my code:
private void doFileUpload(){
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 = 8*1024*1024;
Cursor c = (MainscreenActivity.JEEMAHWDroidDB).query((MainscreenActivity.TABLE_Name), new String[] {
(MainscreenActivity.COL_HwdXml)}, null, null, null, null,
null);
if(c.getCount()!=0){
c.moveToLast();
for(int i=c.getCount()-1; i>=0; i--) {
value=c.getString(0);
}
}
String urlString = value+"/upload_file.php";
try
{
//------------------ CLIENT REQUEST
UUID uniqueKey = UUID.randomUUID();
fname = uniqueKey.toString();
Log.e("UNIQUE NAME",fname);
FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
URL url = new URL(urlString);
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=\"" + fname + "."+extension+"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
System.out.println("BYTES:--------->"+bytesAvailable);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
System.out.println("BUFFER SIZE:--------->"+bufferSize);
buffer = new byte[bufferSize];
System.out.println("BUFFER:--------->"+buffer);
bytesRead = fileInputStream.read(buffer,0,bufferSize);
System.out.println("BYTES READ:--------->"+bytesRead);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
System.out.println("RETURNED");
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
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);
}

Call new loadVideo().execute(); where ever you needed.
And add the following class to do the video loading.
public class loadVideo extends AsyncTask<Void, Void, Void>
{
private final ProgressDialog dialog = new ProgressDialog(
YourActivity.this);
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(false);
this.dialog.show();
}
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
});
}
#Override
protected Void doInBackground(Void... params) {
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 = 8*1024*1024;
Cursor c = (MainscreenActivity.JEEMAHWDroidDB).query((MainscreenActivity.TABLE_Name), new String[] {
(MainscreenActivity.COL_HwdXml)}, null, null, null, null,
null);
if(c.getCount()!=0){
c.moveToLast();
for(int i=c.getCount()-1; i>=0; i--) {
value=c.getString(0);
}
}
String urlString = value+"/upload_file.php";
try
{
//------------------ CLIENT REQUEST
UUID uniqueKey = UUID.randomUUID();
fname = uniqueKey.toString();
Log.e("UNIQUE NAME",fname);
FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
URL url = new URL(urlString);
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=\"" + fname + "."+extension+"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
System.out.println("BYTES:--------->"+bytesAvailable);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
System.out.println("BUFFER SIZE:--------->"+bufferSize);
buffer = new byte[bufferSize];
System.out.println("BUFFER:--------->"+buffer);
bytesRead = fileInputStream.read(buffer,0,bufferSize);
System.out.println("BYTES READ:--------->"+bytesRead);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
System.out.println("RETURNED");
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
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);
}
return null;
}
}

make this call before starting network comm...
ProgressDialog dialog = ProgressDialog.show(this, "", "Loading");
call the below after completion..
dialog.dismiss();
...
Its better to use AsyncTask for network communications

This question might help you. Basically you need to make a ProgressDialog in onPreExecute() method of AsyncTask and dismiss it in onPostExecute().
Upload code will go in the doInBackGround() method of AsyncTask.

Related

Error in uploading audio file to server in Android

Please tell me why am I getting this error?
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable = 0, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://thinksl.com/taughtable/audiopost.php";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(path) );
// 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);
conn.setRequestProperty("userfile",path);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"userfile\";filename=\"" +path+ "\"" + lineEnd);
Log.e("Debug", "Filename: " +path);
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);
}
Log cat
Server Response
{"result":0,"post":[],"files":[],"filename":null,"message":"There was
an error uploading the file, please try again!"}
Use following method to upload audio file to server.
private String uploadAudio(final String filePath) {
String extension = filePath.substring(filePath.lastIndexOf("."));
Log.e(extension);
String response = null;
String final_upload_filename = "sample_audio"+ extension;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "---------------------------14737809831466499882746641449";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(filePath));
URL url = new URL("http://thinksl.com/taughtable/audiopost.php");
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setChunkedStreamingMode(1024);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", final_upload_filename);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"userfile\"; filename=\"" + final_upload_filename + "\"" + lineEnd);
dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
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();
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytessRead;
byte[] bytes = new byte[1024];
while ((bytessRead = is.read(bytes)) != -1) {
baos.write(bytes, 0, bytessRead);
}
byte[] bytesReceived = baos.toByteArray();
baos.close();
is.close();
response = new String(bytesReceived);
Log.e("Server Response" + response);
} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
return response;
}
I hope it helps!
Why don't you try like this,
try {
HttpClient httpClient = new DefaultHttpClient();
String url = "http://thinksl.com/taughtable/audiopost.php";
HttpPost httppost = new HttpPost(url);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", new FileBody(new File(path)));
reqEntity.addPart("filename", final_upload_filename);
httppost.setEntity(reqEntity);
HttpResponse response = httpClient.execute(httppost);
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);
}
System.out.println("Response: " + s);
Log.e(TAG, "Response: " + s);
status = "" + s;
} catch (Exception e) {
e.printStackTrace();
}

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.

Android: updating progressbar for file upload

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.

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

Working with web service?

I want to copy all the video files on my server & save it in the web contents folder of a web service , so that it can be visible to all later on !
How should i proceeed ?
Basically you need two sides. The first one is on Android. You have to send (Do it in an ASyncTask e.x.) the data to your webservice. Here I made a little method for you, which sends a file and some additional POST values to an URL:
private boolean handleFile(String filePath, String mimeType) {
HttpURLConnection connection = null;
DataOutputStream outStream = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String urlString = "http://your.domain.com/webservice.php";
try {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(new File(filePath));
} catch(FileNotFoundException e) { }
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outStream = new DataOutputStream(connection.getOutputStream());
// Some POST values
outStream.writeBytes(addParam("additional_param", "some value");
outStream.writeBytes(addParam("additional_param 2", "some other value");
// The file with the name "uploadedfile"
outStream.writeBytes(twoHyphens + boundary + lineEnd);
outStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + filePath +"\"" + lineEnd + "Content-Type: " + mimeType + lineEnd + "Content-Transfer-Encoding: binary" + lineEnd);
outStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outStream.writeBytes(lineEnd);
outStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
outStream.flush();
outStream.close();
} catch (MalformedURLException e) {
Log.e("APP", "MalformedURLException while sending\n" + e.getMessage());
} catch (IOException e) {
Log.e("APP", "IOException while sending\n" + e.getMessage());
}
// This part checks the response of the server. If its "UPLOAD OK" the method returns true
try {
inStream = new DataInputStream( connection.getInputStream() );
String str;
while (( str = inStream.readLine()) != null) {
if(str=="UPLOAD OK") {
return true;
} else {
return false;
}
}
inStream.close();
} catch (IOException e){
Log.e("APP", "IOException while sending\n" + e.getMessage());
}
return false;
}
Now, we have got the other side: http://your.domain.com/webservice.php
Your server. It needs some logic, for example in PHP, to handle the sent POST request.
Something like this would work:
<?php
$target_path = "videos/";
$target_path = $target_path.'somename.3gp';
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
exit("UPLOAD OK");
} else {
exit("UPLOAD NOT OK");
}
?>

Categories

Resources