Android上传文件到服务器--带进度条

来源:互联网 发布:现货投资交易软件 编辑:程序博客网 时间:2024/06/01 17:33

本人以前是学C#的,所以服务器端有了一般处理程序进行接收文件流操作。

import android.app.ProgressDialog;import android.content.Context;import android.os.AsyncTask;import android.os.Handler;import android.util.Log;import android.widget.Toast;/** * 文件上传 */public class UploadUtilTask extends AsyncTask<Object,Integer,String> {private static final String TAG = "xing";private static final int TIME_OUT = 10 * 1000; // 请求时间private static final String CHARSET = "utf-8"; // 设置编码private static String requestUrl = "http://192.168.1.189:8095/UploadFile.ashx";Context context;private ProgressDialog dialog = null;File mFile = null;long totalSize = 0;  //文件大小String cardGuid = null;Handler handler;public UploadUtilTask(Context _context){context = _context;}@Overrideprotected void onPreExecute() {// TODO Auto-generated method stubsuper.onPreExecute();dialog = new ProgressDialog(context);dialog.setTitle("正在上传录音文件...");dialog.setMessage("0K/"+totalSize/1000+"k");dialog.setIndeterminate(false);dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);dialog.setProgress(0);dialog.show();}public void uploadFile(File file,String _cardGuid,Handler _handler) {handler = _handler;mFile = file;//mFile = new File("mnt/sdcard/com.magical.carduola/123.mp3");totalSize = mFile.length();cardGuid = _cardGuid;}@Overrideprotected String doInBackground(Object... arg0) {String result = null;String BOUNDARY = UUID.randomUUID().toString().replace("-", ""); // 边界标识,随机生成String PREFIX = "--", LINE_END = "\r\n";// 内容类型  audio/x-realaudioString CONTENT_TYPE = "audio/mpeg";try {URL url = new URL(requestUrl);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setChunkedStreamingMode(128*1024);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", "text/plain");  conn.setRequestProperty("Connect-Type","multipart/form-data;boundary="+ BOUNDARY);if (mFile != null) {DataOutputStream dos = new DataOutputStream(conn.getOutputStream());StringBuffer sb = new StringBuffer();sb.append(PREFIX);sb.append(BOUNDARY);sb.append(LINE_END);sb.append("Content-Disposition:form-data;name=\"file\";filename=\""+ mFile.getName() + "\"" + LINE_END);sb.append("Content-Type:"+CONTENT_TYPE+";"+ LINE_END);sb.append(LINE_END);dos.write(sb.toString().getBytes());FileInputStream is = new FileInputStream(mFile);byte[] bytes = new byte[1024];int len = 0,length = 0,progress = 0;while ((len = is.read(bytes)) != -1) {dos.write(bytes, 0, len);length+=len;progress = (int) ((length * 100) / totalSize);publishProgress(progress,(int)length);}publishProgress(100,(int)length);is.close();dos.write(LINE_END.getBytes());dos.write(LINE_END.getBytes());byte[] end_data = (PREFIX + BOUNDARY + PREFIX).getBytes();dos.write(end_data);dos.flush();/** 获取响应码,200=成功 */int res = conn.getResponseCode();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);} else {Log.e(TAG, "request error");}}} catch (Exception e) {Log.i(TAG, "error"+e.getMessage());}return result;}@Overrideprotected void onProgressUpdate(Integer... progress) { dialog.setProgress(progress[0]); dialog.setMessage(progress[1]/1000+"k/"+totalSize/1000+"k"); }@Overrideprotected void onPostExecute(String result) {// TODO Auto-generated method stubsuper.onPostExecute(result);try {        if("success".equals(result)){        handler.obtainMessage(ShareVoiceActivity.Upload_SUCCESS).sendToTarget();        Toast.makeText(context,"上传成功!",Toast.LENGTH_LONG ).show();        this.cancel(true);        }else{        Toast.makeText(context,"上传失败!",Toast.LENGTH_LONG ).show();        }} catch (Exception e) {}finally{try{dialog.dismiss();}catch(Exception e){}}}}

不多解释,在Activity中实例化UploadUtilTask一个对象,然后execute() 即可

0 0
原创粉丝点击