Skip to content

Instantly share code, notes, and snippets.

@diegogurgel
Created July 25, 2014 22:18
Show Gist options
  • Save diegogurgel/07129f0c67710c677d80 to your computer and use it in GitHub Desktop.
Save diegogurgel/07129f0c67710c677d80 to your computer and use it in GitHub Desktop.
Upload Android with progress
package com.diegogurgel.upload;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.HeterogeneousExpandableList;
import android.widget.Toast;
public class FileUpload extends AsyncTask<File, Integer, Boolean> {
@Override
protected Boolean doInBackground(File... files) {
try{
Log.i("TENTANDO", ":)");
File file = files[0];
FileInputStream fileInputStream = new FileInputStream(file);
byte[]bytes = new byte[(int) file.length()];
fileInputStream.read(bytes);
fileInputStream.close();
URL postUrl = new URL("http://www.uploadify.com/uploadify/uploadify.php");
HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
connection.setRequestMethod("POST");
OutputStream outputStream = connection.getOutputStream();
int bufferLength = 1024;
for (int i = 0; i < bytes.length; i+=bufferLength) {
int progress = (int)((i/(float)bytes.length)*100);
publishProgress(progress);
if(bytes.length-i>=bufferLength){
outputStream.write(bytes, i, bufferLength);
}else{
outputStream.write(bytes, i, bytes.length-i);
}
}
publishProgress(100);
outputStream.close();
outputStream.flush();
InputStream inputStream = connection.getInputStream();
//Ler resposta
inputStream.close();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
Log.i("PROGRESSO", values[0]+"");
//super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment