问题描述
- Okhttp上传多图,大于4.5M失败
-
小一点的图片可以上传成功,大了在onResponse中输出是一个404页面,有没有小伙伴知道怎么解决,或者有图片上传的框架,多谢了,下面是我用的上传代码public static String uploadImages(int parameter, String url, Map<String, String> map, List<String> paths, final Handler handler) { // 参数类型 MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); // 创建OkHttpClient实例 OkHttpClient client = new OkHttpClient(); client.setReadTimeout(1000, TimeUnit.MINUTES); client.setWriteTimeout(1000, TimeUnit.MINUTES); client.setConnectTimeout(1000, TimeUnit.MINUTES); MultipartBuilder builder = new MultipartBuilder() .type(MultipartBuilder.FORM); // 遍历map中所有参数到builder if (map != null) { for (String key : map.keySet()) { builder.addFormDataPart(key, map.get(key)); } } if (paths != null) { switch (parameter) { case 1: for (int i = 0; i < paths.size(); i++) { File file = new File(paths.get(i)); builder.addFormDataPart("img" + (i + 1), file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file)); } break; case 2: for (String path : paths) { builder.addFormDataPart("articleImages", path, RequestBody.create(MEDIA_TYPE_PNG, new File(path))); } break; case 3: for (String path : paths) { builder.addFormDataPart("lawCeritificateImage", path, RequestBody.create(MEDIA_TYPE_PNG, new File(path))); } break; case 4: // 更换头像 for (String path : paths) { builder.addFormDataPart("imgs", path, RequestBody.create(MEDIA_TYPE_PNG, new File(path))); } break; case 5: // 空间图片上传 for (String path : paths) { builder.addFormDataPart("imgs", path, RequestBody.create(MEDIA_TYPE_PNG, new File(path))); } break; default: break; } } // 构建请求体 RequestBody requestBody = builder.build(); // 构建请求 Request request = new Request.Builder().url(url)// 地址 .post(requestBody)// 添加请求体 .build(); // 发送异步请求,同步会报错,Android4.0以后禁止在主线程中进行耗时操作 client.newCall(request).enqueue(new Callback() { public void onFailure(Request arg0, IOException arg1) { Log.i("dd", "error" + arg1.toString()); Message msg = Message.obtain(); msg.obj = arg1.toString(); msg.what = Constants.UPLOAD_ERROR; handler.sendMessage(msg); } public void onResponse(Response response) throws IOException { String con = response.body().string(); Message msg = Message.obtain(); msg.obj = con; msg.what = Constants.UPLOAD_SUC; handler.sendMessage(msg); } }); return result; }
解决方案
后台输出错误,查看后台是否限制文件的大小
时间: 2024-10-26 14:07:17