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

本人以前是学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;
	}
	
	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.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;
	}
	
	@Override
	protected String doInBackground(Object... arg0) {
		String result = null;
		String BOUNDARY = UUID.randomUUID().toString().replace("-", ""); // 边界标识,随机生成
		String PREFIX = "--", LINE_END = "\r\n";
		// 内容类型  audio/x-realaudio
		String 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;
	}
	
	@Override
	protected void onProgressUpdate(Integer... progress) {
		 dialog.setProgress(progress[0]);
		 dialog.setMessage(progress[1]/1000+"k/"+totalSize/1000+"k"); 
	}
	
	@Override
	protected void onPostExecute(String result) {
		// TODO Auto-generated method stub
		super.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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值