OkhttpUtils单、多文件上传

OkhttpUtils单文件上传

public static void upLoadToServer(final Context context, HashMapparams,final String url, String filePath, final ArrayList list, final HttpCallBackListener listener) {
    if (NetUtils.isConnected(context)) {
        Map headers = new HashMap<>();
        headers.put("Content-Disposition", "form-data;filename=enctype");
        File file = new File(filePath);
        if (!file.exists()) {
            MyToast.showMessage("文件不存在,请修改文件路径");
            return;
        }
        String filename = file.getName();
        OkHttpUtils.post().params(params)
                .headers(headers)
                .addFile("mFile", filename, file)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                    }
                });
    }
}

 OkhttpUtils多文件上传,addFile中name 要变,要不只是传第一张图片后面的不传,类似Map键值存储

public PostFormBuilder addFile(String name, String filename, File file)
{
    files.add(new FileInput(name, filename, file));
    return this;
}

 

public static void upLoadToServer(final Context context, final String url, final Map params, final ArrayList list, final HttpCallBackListener listener) {
    if (NetUtils.isConnected(context)) {
        Map headers = new HashMap<>();
        headers.put("Content-Disposition", "form-data;filename=enctype");
        PostFormBuilder builder = OkHttpUtils.post();
        builder.url(url);
        for (int i = 0; i < list.size(); i++) {
            File file = new File(list.get(i));
            if (!file.exists()) {
                MyToast.showMessage("文件不存在,请修改文件路径");
                return;
            }
            String filename = file.getName();
            builder.addFile("mFile"+i, filename, file);
        }

        builder.params(params)
                .headers(headers)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        
                    }

                    @Override
                    public void onResponse(String response, int id) {
                    }
                });
    }
}

 

你可能感兴趣的:(网络请求)