上传多张图片到服务器

有些话、适合烂在心里 提交于 2019-11-26 13:22:44
      List<File> imageLists = new ArrayList<>();     File photo1file = new File(getContext().getExternalFilesDir("photos").getPath(), photo1.toFileName());
    File photo2file = new File(getContext().getExternalFilesDir("photos").getPath(), photo2.toFileName());
    private static final MediaType MEDIA_TYPE_IAMGE = MediaType.parse("image/*");    /**     * okHttp post异步请求表单提交     *     * @param actionUrl 接口地址     * @param paramsMap 请求参数     * @param fileParamName 图片参数的名字     * @param imageLists 图片参数的列表     * @param callBack  请求返回数据回调     * @param <T>       数据泛型     * @return     */    public <T> Call requestPostByAsynWithImageList(String actionUrl, HashMap<String, String> paramsMap, String fileParamName, List<File> imageLists, final ReqCallBack<T> callBack) {        try {            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);            for (String key : paramsMap.keySet()) {//                builder.add(key, paramsMap.get(key));                builder.addFormDataPart(key,paramsMap.get(key));            }            for(File image : imageLists) {                builder.addFormDataPart(fileParamName, image.getName(), RequestBody.create(MEDIA_TYPE_IAMGE, image));            }            RequestBody formBody = builder.build();            String requestUrl = String.format("%s/%s", WebUrls.baseurl, actionUrl);            final Request request = addHeaders().url(requestUrl).post(formBody).build();            final Call call = mOkHttpClient.newCall(request);            call.enqueue(new Callback() {                @Override                public void onFailure(Call call, IOException e) {                    failedCallBack("访问失败", callBack);                    Log.e(TAG, e.toString());                }                @Override                public void onResponse(Call call, Response response) throws IOException {                    if (response.isSuccessful()) {                        String string = response.body().string();                        String header=response.header("Content-MD5");                        Log.e(TAG, "response ----->" + string);                        successCallBack((T) string,header, callBack);                    } else {                        failedCallBack("服务器错误", callBack);                    }                }            });            return call;        } catch (Exception e) {            Log.e(TAG, e.toString());        }        return null;    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!