MultipartBody uploadFile 本地上传

/**
 * post方式二:stirng类型参数和上传文件参数
 */
public void uploadFile(Map params) {//标注 集合必须包含 url 
    //post请求方式二:multipart/form-data(不仅能够上传string类型的参数,还可以上传文件(流的形式,file))
    OkHttpClient okHttpClient1 = new OkHttpClient();//推荐使用多线程
    MultipartBody.Builder builder1 = new MultipartBody.Builder();//构建者模式
    
    builder1.setType(MultipartBody.FORM);//传输类型
    for (Map.Entry stringObjectEntry : params.entrySet()) {//没有判空
        String key = stringObjectEntry.getKey();
        Object value = stringObjectEntry.getValue();
        if (value instanceof File) {//如果请求的值是文件
            File file = (File) value;
            //MediaType.parse("application/octet-stream")以二进制的形式上传文件                                        
            builder1.addFormDataPart("jokeFiles", ((File) value).getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file));
        } else {//如果请求的值是string类型
            if(!"url".equals(key)){
                builder1.addFormDataPart(key, value.toString());
            }
        }
    }
    //进行请求
    Request request1 = new Request.Builder().post(builder1.build()).url((String) params.get("url")).build();
    okHttpClient1.newCall(request1).enqueue(new Callback() {
        @Override
        public void onFailure(okhttp3.Call call, IOException e) {

        }

        @Override
        public void onResponse(okhttp3.Call call, Response response) throws IOException {

            if (response.isSuccessful()){//200-300

            }
        }
    });

你可能感兴趣的:(MultipartBody uploadFile 本地上传)