一般来说,目前在手机端上传图片,方法挺多的,不过常用的就是一个文件流,另一个是二进制转base64的字符流,下面分享一下方法
网络上都是千篇一律的写法,对于上传过程中失败的问题也很少提及,上传失败的bug,主要的原因当然是编码字符的问题了,一般网上都没有介绍,记得要将base64的字符串 转化一下为utf-8,要不然会导致上传失败
1.
2. public static String httpPostBase64(byte[] data, String url,String uid,String blog) {
3. String str=null;
4. try {
5.
6. HttpPost httpRequest = new HttpPost(url);
7.
8.
9.
10.
11.
12. List params = new LinkedList();
13. params.add(new BasicNameValuePair("uid", uid));
14. params.add(new BasicNameValuePair("blog", blog));
15. if(data!=null){
16. String data1 = Base64.encodeToString(data, 0, data.length,Base64.DEFAULT);
17. params.add(new BasicNameValuePair("img",URLEncoder.encode(data1,"UTF-8")));
18. }
19.
20.
21.
22.
23.
24. httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
25.
26.
27.
28. HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
29.
30.
31.
32. if (httpResponse.getStatusLine().getStatusCode() != 200) {
33.
34. Log.d("Code", httpResponse.getStatusLine().toString());
35.
36. return str;
37.
38. }else{
39. HttpEntity httpEntity=httpResponse.getEntity();
40. str = EntityUtils.toString(httpEntity,"UTF-8");
41. System.out.println("-------------------"+str);
42. }
43.
44. } catch (Exception e) {
45.
46. for (StackTraceElement s : e.getStackTrace())
47.
48. Log.d("Exception", s.toString());
49.
50. Log.d("Exception", e.getLocalizedMessage());
51.
52. return str;
53.
54. }
55.
56. return str;
57.
58. }
标签:String,data,base64,params,str,new,android,上传
From: https://blog.51cto.com/u_548275/6237806