class FileUploadTask extends AsyncTask<Object, Integer, String> {

// private ProgressDialog dialog = null;
Dialog dialog = new Dialog(PhotoUploadActivity.this,
R.style.ProgressBarDialog);

String BOUNDARY = UUID.randomUUID().toString(); // 邊界標識 隨機生成
String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 內容類型

File uploadFile = new File(filePath);
long totalSize = uploadFile.length(); // Get size of file, bytes

ProgressBar mProgress;
TextView mProgress_txt;

@Override
protected void onPreExecute() {
/*
* dialog = new ProgressDialog(PhotoUploadActivity.this);
* dialog.setTitle("正在上傳...");
* dialog.setMessage("0k/"+totalSize/1000+"k");
* dialog.setIndeterminate(false);
* dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
* dialog.setProgress(0); dialog.show();
*/

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_photo_progressbar);
dialog.setCancelable(true);
DisplayMetrics dm = PhotoUploadActivity.this
.getApplicationContext().getResources().getDisplayMetrics();
int width = dm.widthPixels;
WindowManager.LayoutParams params = dialog.getWindow()
.getAttributes();
params.width = 9 * width / 10;
dialog.getWindow().setAttributes(params);
mProgress = (ProgressBar) dialog
.findViewById(R.id.progress_horizontal);
mProgress_txt = (TextView) dialog.findViewById(R.id.progress_txt);
mProgress.setMax(100);
mProgress.setProgress(0);
mProgress.setIndeterminate(false);
dialog.setCancelable(false);// 設置這個對話框不能被用戶按[返回鍵]而取消掉,但測試發現如果用戶按了KeyEvent.KEYCODE_SEARCH,對話框還是會Dismiss掉
// 由於設置alertDialog.setCancelable(false);
// 發現如果用戶按了KeyEvent.KEYCODE_SEARCH,對話框還是會Dismiss掉,這裏的setOnKeyListener作用就是屏蔽用戶按下KeyEvent.KEYCODE_SEARCH
dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_SEARCH) {
return true;
} else {
return false; // 默認返回 false
}
}
});
dialog.show();
dialog.getWindow()
.setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
}

@Override
protected String doInBackground(Object... arg0) {
String result = "";
long length = 0;
int progress;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 10 * 1024;// 10KB

try {
URL url = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
// Set size of every block for post
conn.setChunkedStreamingMode(128 * 1024);// 128KB
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); // 允許輸入流
conn.setDoOutput(true); // 允許輸出流
conn.setUseCaches(false); // 不允許使用緩存
conn.setRequestMethod("POST"); // 請求方式
conn.setRequestProperty("Charset", CHARSET); // 設置編碼
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE
+ ";boundary=" + BOUNDARY);

if (uploadFile != null) {

/**
* 當文件不为空,把文件包裝並且上傳
*/
DataOutputStream dos = new DataOutputStream(conn
.getOutputStream());
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 這裏重點注意: name裏面的值为服務端需要key 只有這個key 才可以得到對應的文件
* filename是文件的名字,包含後綴名的 比如:abc.png
*/

sb.append("Content-Disposition: form-data; name=\"myFile\"; filename=\"" + java.net.URLEncoder.encode(uploadFile
.getName(), "UTF-8") + "\"" + LINE_END);
sb.append("Content-Type: application/octet-stream; charset="+ CHARSET + LINE_END);
sb.append(LINE_END);

dos.write(sb.toString().getBytes());
InputStream is = new FileInputStream(uploadFile);
bytesAvailable = is.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);// 設置每次寫入的大小
buffer = new byte[bufferSize];
// Read file
bytesRead = is.read(buffer, 0, bufferSize);

while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
length += bufferSize;
Thread.sleep(500);
progress = (int) ((length * 100) / totalSize);
publishProgress(progress, (int) length);

bytesAvailable = is.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = is.read(buffer, 0, bufferSize);
}
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
// 請求結束標志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
.getBytes();
dos.write(end_data);
dos.flush();
publishProgress(100, (int) length);
/**
* 獲取響應碼 200=成功 當響應成功,獲取響應的流
*/
int res = conn.getResponseCode();
Log.e(TAG, "response code:" + res);
if (res == 200) {
Log.e(TAG, "request success");
InputStream input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
}
result = sb1.toString();
Log.e(TAG, "result : " + result + "fffff"
+ new File(filePath).getName() + "呵呵呵" + sb1);
} else {
Log.e(TAG, "request error");
}
}
} catch (Exception ex) {

}
return result;
}

@Override
protected void onProgressUpdate(Integer... progress) {
// dialog.setProgress(progress[0]);
// dialog.setMessage(progress[1]/1000+"k/"+totalSize/1000+"k");
Log.i(TAG, "已經上傳----->" + progress[1] / 1000 + "k/" + totalSize
/ 1000 + "k");
mProgress.setProgress(progress[0]);
mProgress_txt.setText(progress[1] / 1000 + "k/" + totalSize / 1000
+ "k" + "  " + progress[1] * 100 / totalSize + "%");
}

@Override
protected void onPostExecute(String result) {
try {

if ("1".equals(result)) {
Toast.makeText(PhotoUploadActivity.this, "上傳成功!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(PhotoUploadActivity.this, "上傳失敗!",
Toast.LENGTH_LONG).show();
}

} catch (Exception e) {

} finally {
try {
dialog.dismiss();
} catch (Exception e) {

}
}
}

創作者介紹
創作者 shadow 的頭像
shadow

資訊園

shadow 發表在 痞客邦 留言(0) 人氣()