package com.tianlei.httpUrlConnection_PHPUpload;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
public class Upload{
/** Called when the activity is first created. */
/**
* Upload file to web server with progress status, client: android;
* server:php
* **/
private String urlServer = "http://120.126.16.52/uploadfile.php"; //the server address to process the uploaded file
public String filepath; //the file path to upload
private Context c;
public Upload(Context c, String filepath){
this.c = c;
this.filepath = filepath;
}
//开始下载并显示进度条
public void startUpload(){
FileUploadTask fileUploadTask = new FileUploadTask();
fileUploadTask.execute();
}
// show Dialog method
/*private void showDialog(String mess) {
new AlertDialog.Builder(c).setTitle("Message")
.setMessage(mess)
.setNegativeButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}*/
class FileUploadTask extends AsyncTask<Object, Integer, Void> {
private ProgressDialog dialog = null;
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
File uploadFile = new File(filepath);
long totalSize = uploadFile.length(); // Get size of file, bytes
/*该方法将在执行实际的后台操作前被UI thread调用。可以在该方法中做一些准备工作,
* 如在界面上显示一个进度条。 */
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(c);
dialog.setMessage("正在上传...");
dialog.setIndeterminate(false);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.show();
}
/*将在onPreExecute 方法执行后马上执行,该方法运行在后台线程中。这里将主要负责执行
* 那些很耗时的后台计算工作。可以调用 publishProgress方法来更新实时的任务进度。
* 该方法是抽象方法,子类必须实现。*/
@Override
protected Void doInBackground(Object... arg0) {
long length = 0;
int progress;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 256 * 1024;// 256KB
try {
FileInputStream fileInputStream = new FileInputStream(new File(
filepath));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Set size of every block for post
connection.setChunkedStreamingMode(256 * 1024);// 256KB
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(
connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream
.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ filepath + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
length += bufferSize;
progress = (int) ((length * 100) / totalSize);
//调用 publishProgress方法来更新实时的任务进度
publishProgress(progress);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
//进度条100,下载完成
publishProgress(100);
/*通过使用Dialog()对话框显示进度条*/
// Responses from the server (code and message)
//int serverResponseCode = connection.getResponseCode();
//String serverResponseMessage = connection.getResponseMessage();
/* 将Response显示于Dialog */
// Toast toast = Toast.makeText(UploadtestActivity.this, ""
// + serverResponseMessage.toString().trim(),
// Toast.LENGTH_LONG);
// showDialog(serverResponseMessage.toString().trim());
/* 取得Response内容 */
// InputStream is = connection.getInputStream();
// int ch;
// StringBuffer sbf = new StringBuffer();
// while ((ch = is.read()) != -1) {
// sbf.append((char) ch);
// }
//
// showDialog(sbf.toString().trim());
fileInputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
// Exception handling
// showDialog("" + ex);
// Toast toast = Toast.makeText(UploadtestActivity.this, "" +
// ex,
// Toast.LENGTH_LONG);
}
return null;
}
/*在publishProgress方法被调用后,UI thread将调用这个方法从而在界面上展示任务
*的进展情况,例如通过一个进度条进行展示。*/
@Override
protected void onProgressUpdate(Integer... progress) {
dialog.setProgress(progress[0]);
}
/*在doInBackground 执行完成后,onPostExecute 方法将被UI thread调用,
*后台的计算结果将通过该方法传递到UI thread.*/
@Override
protected void onPostExecute(Void result) {
try {
dialog.dismiss(); //dismiss the dialog
// TODO Auto-generated method stub
} catch (Exception e) {
}
}
}
}
转载于:https://my.oschina.net/u/1014520/blog/194692