Volley-XUtils-OkHttp三种方式实现单张多张图片上传

OkHttp可以作为Volley底层传输协议,速度更快,传大量图片建议使用。OkHttp更多功能请看OkHttp的使用

xUtils 支持大文件上传,更全面的http请求协议支持(10种谓词),拥有更加灵活的ORM,更多的事件注解支持且不受混淆影响...

xUtils一共有4大功能:注解模块,网络模块,图片加载模块,数据库模块。相关请看xUtils框架的使用博客

使用Volley上传,猪哟是继承volley的Request类,然后通过使用httpmim的MultipartEntity类对文件参数进行封装。

Volley更多功能请看Volley框架使用

所需的jar包:

 

httpclient-4.3.5.jarandroid-async-http-1.4.4.jar

httpcore-4.3.2.jar,        httpmime-4.3.5

okhttp.jarokio.jarvolley.jarxUtils-2.6.2.jar

 

OkHttp代码:

private static final Handler handler = new Handler(Looper.getMainLooper());  
  
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/*");  
  
private static final OkHttpClient client = new OkHttpClient.Builder()  
        .addInterceptor(new Interceptor() {  
            @Override  
            public Response intercept(Chain chain) throws IOException {  
                okhttp3.Request request = chain.request().newBuilder()  
                        .build();  
                return chain.proceed(request);  
            }  
        }).readTimeout(15, TimeUnit.SECONDS)// 设置读取超时时间  
        .writeTimeout(15, TimeUnit.SECONDS)// 设置写的超时时间  
        .connectTimeout(15, TimeUnit.SECONDS)// 设置连接超时时间  
        .build();  
  
// 上传图片公有方法  
private final static void uploadImgAndParameter(Map<String, Object> map,  
        String url) {  
  
    // mImgUrls为存放图片的url集合  
    MultipartBody.Builder builder = new MultipartBody.Builder()  
            .setType(MultipartBody.FORM);  
  
    if (null != map) {  
        for (Map.Entry<String, Object> entry : map.entrySet()) {  
            if (entry.getValue() != null) {  
                if (entry.getValue() instanceof File) {  
                    File f = (File) entry.getValue();  
                    builder.addFormDataPart(entry.getKey(), f.getName(),  
                            RequestBody.create(MEDIA_TYPE_PNG, f));  
                } else {  
                    builder.addFormDataPart(entry.getKey(), entry  
                            .getValue().toString());  
                }  
            }  
  
        }  
    }  
    // 创建RequestBody  
    RequestBody body = builder.build();  
    final okhttp3.Request request = new okhttp3.Request.Builder().url(url)// 地址  
            .post(body)// 添加请求体  
            .build();  
    client.newCall(request).enqueue(new okhttp3.Callback() {  
  
        @Override  
        public void onResponse(Call call, final Response response)  
                throws IOException {  
            final String data = response.body().string();  
            Log.i(TAG, "上传照片成功-->" + data);  
            call.cancel();// 上传成功取消请求释放内存  
        }  
  
        @Override  
        public void onFailure(Call call, final IOException e) {  
            Log.i(TAG, "上传失败-->" + e.getMessage());  
            call.cancel();// 上传失败取消请求释放内存  
        }  
  
    });  
  
} 

XUtils:

HttpUtils http = new HttpUtils();  
        RequestParams params = new RequestParams();  
        params.addBodyParameter("c", "comment");  
        params.addBodyParameter("a", "add");  
        params.addBodyParameter("uid", "1000191");  
        params.addBodyParameter("dataid", "1114");  
        params.addBodyParameter("message", "你好");  
        params.addBodyParameter("datatype", "goodsid");  
        for (int i = 0; i < 2; i++) {  
            params.addBodyParameter("filedata" + i, file[i]);  
        }  
        http.send(HttpRequest.HttpMethod.POST, url, params,  
                new RequestCallBack<String>() {  
  
                    @Override  
                    public void onFailure(HttpException arg0, String arg1) {  
  
                    }  
  
                    @Override  
                    public void onSuccess(ResponseInfo<String> arg0) {  
                        Log.i(TAG, arg0.result.toString());  
                    }  
  
                });  

Volley:

public static void addPutUploadFileRequest(final Map<String, File> files,  
            final Map<String, String> params,  
            final Listener<String> responseListener,  
            final ErrorListener errorListener) {  
        if (null == url || null == responseListener) {  
            return;  
        }  
  
        MultiPartStringRequest multiPartRequest = new MultiPartStringRequest(  
                Request.Method.POST, url, responseListener, errorListener) {  
  
            @Override  
            public Map<String, File> getFileUploads() {  
                return files;  
            }  
  
            @Override  
            public Map<String, String> getStringUploads() {  
                return params;  
            }  
  
        };  
  
        mSingleQueue.add(multiPartRequest);  
    }  
  
    Listener<JSONObject> mResonseListener = new Listener<JSONObject>() {  
  
        @Override  
        public void onResponse(JSONObject response) {  
            Log.i(TAG + "1", response.toString());  
        }  
    };  
  
    Listener<String> mResonseListenerString = new Listener<String>() {  
  
        @Override  
        public void onResponse(String response) {  
            Log.i(TAG + "2", response.toString());  
        }  
    };  
  
    ErrorListener mErrorListener = new ErrorListener() {  
  
        @Override  
        public void onErrorResponse(VolleyError error) {  
            if (error != null) {  
                if (error.networkResponse != null)  
                    Log.i(TAG + "3", " error "  
                            + new String(error.networkResponse.data));  
            }  
        }  
    };  

不要忘记在AndroidManifest.xml加权限哦!

 <uses-permissionandroid:name="android.permission.INTERNET"/>

 <uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 

本人测试全部成功了的

由于代码太多,完整代码未给出,源码直接下载即可

 

源码点击下载:  https://github.com/DickyQie/android-picture-upload

 
posted @ 2016-12-22 16:17  切切歆语  阅读(6489)  评论(0编辑  收藏  举报