如何实现在Android文件上传进度条

如何实现在Android文件上传进度条,第1张

实现在android实现带进度条的上传效果效果如图:用到以下两个类就可实现带进度条的文件上传:1、CustomMultiPartEntity extends MultipartEntity, 2、模橘HttpMultipartPost extends AsyncTask代码如下: import java/UploadImage.php") try{CustomMultipartEntitymultipartContent = newCustomMultipartEntity(newProgressListener() { @Overridepublic void transferred(longnum){publishProgress((int) ((num / (float) totalSize) * 100))}}) // We use FileBody to transfer an imagemultipartContent.addPart("uploaded_file", newFileBody(newFile(m_userSelectedImagePath)))totalSize= multipartContent.getContentLength() /嫌码销/ Send ithttpPost.setEntity(multipartContent)HttpResponseresponse = httpClient.execute(httpPost, httpContext)String serverResponse = EntityUtils.toString(response.getEntity()) ResponseFactoryrp = newResponseFactory(serverResponse)return(TypeImage) rp.getData()} catch(Exception e) {System.out.println(e)}returnnull} @OverrideprotectedvoidonProgressUpdate(Integer... progress){pd.setProgress((int) (progress[0]))} @OverrideprotectedvoidonPostExecute(TypeUploadImageui) {pd.dismiss()}}在 transferred()函数中调用publishProgress((int) ((num / (float) totalSize) * 100))在onProgressUpdate()实现上传进度的芹游更新 *** 作

可使用android自带的httpclient框架实现,附件中已经现成的示例代码,带上传进度。

1. GET 方式传递参数

//先将参数放入List,再对参数进友滚行URL编码

List<BasicNameValuePair>params = new LinkedList<BasicNameValuePair>()

params.add(new BasicNameValuePair("param1", "数据"))    //增薯告铅加参数1

params.add(new BasicNameValuePair("param2", "value2"))//增加参数2

String param = URLEncodedUtils.format(params, "UTF-8")//对数好参数编码

String baseUrl = "服务器接口完整URL"

HttpGet getMethod = new HttpGet(baseUrl + "?" + param)//将URL与参数拼接

HttpClient httpClient = new DefaultHttpClient()

try {

  HttpResponse response = httpClient.execute(getMethod)//发起GET请求

  Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode())//获取响应码

  Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"))//获取服务器响应内容

} catch (ClientProtocolException e) {

  e.printStackTrace()

} catch (IOException e) {

  e.printStackTrace()

}

2. POST方式 方式传递参数

//和GET方式一样,先将参数放入List

params = new LinkedList<BasicNameValuePair>()

params.add(new BasicNameValuePair("param1", "Post方法"))//增加参数1

params.add(new BasicNameValuePair("param2", "第二个参数"))//增加参数2

try {

  HttpPost postMethod = new HttpPost(baseUrl)//创建一个post请求

  postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8"))//将参数填入POST Entity中

  HttpResponse response = httpClient.execute(postMethod)//执行POST方法

  Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode())//获取响应码

  Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"))//获取响应内容

} catch (UnsupportedEncodingException e) {

  e.printStackTrace()

} catch (ClientProtocolException e) {

  e.printStackTrace()

} catch (IOException e) {

  e.printStackTrace()

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12245702.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-22
下一篇 2023-05-22

发表评论

登录后才能评论

评论列表(0条)

保存