长话短说,不深入解释了,官方给的上传案例代码:
privatestaticfinalStringIMGUR_CLIENT_ID="...";privatestaticfinalMediaTypeMEDIA_TYPE_PNG=MediaType.parse("image/png");privatefinalOkHttpClientclient=newOkHttpClient();publicvoidrun()throwsException{//UsetheimgurimageuploadAPIasdocumentedat/endpoints/imageRequestBodyrequestBody=newMultipartBuilder().type(MultipartBuilder.FORM).addPart(Headers.of("Content-Disposition","form-data;name=\"title\""),RequestBody.create(null,"SquareLogo")).addPart(Headers.of("Content-Disposition","form-data;name=\"image\""),RequestBody.create(MEDIA_TYPE_PNG,newFile("website/static/logo-square.png"))).build();Requestrequest=newRequest.Builder().header("Authorization","Client-ID"+IMGUR_CLIENT_ID).url("/3/image").post(requestBody).build();Responseresponse=client.newCall(request).execute();if(!response.isSuccessful())thrownewIOException("Unexpectedcode"+response);System.out.println(response.body().string());}
上面这个代码上传文件在Java服务器端用springboot的 MultiPart解析不到上传的文件,用PythonDjango,问题亦然。
找到了一个泡网同学的代码:
做了改动1:
RequestBodyrequestBody=newMultipartBuilder().type(MultipartBuilder.FORM).addPart(Headers.of("Content-Disposition","form-data;name=\"UserId\""),RequestBody.create(null,UserId)).addPart(Headers.of("Content-Disposition","form-data;name=\"SecurityCode\""),RequestBody.create(null,SecurityCode)).addPart(Headers.of("Content-Disposition","form-data;name=\"File\";filename=\"avatar_upload.jpg\""),RequestBody.create(MediaType.parse("image/jpeg"),file)).build();
改为以上代码后,Django请求解析可以找到文件了,Spring boot的multipart任然找不到文件信息。
改动1的改动点是:文件的Header信息里面必须有上传文件的名字,当然这个名字其实是随便起的,一般后缀保持正确即可。
这个时候不得不再参考泡网同学的代码,做了修改2:
RequestBodyrequestBody=newMultipartBuilder().type(MultipartBuilder.FORM).addPart(Headers.of("Content-Disposition","form-data;name=\"UserId\""),RequestBody.create(null,UserId)).addPart(Headers.of("Content-Disposition","form-data;name=\"SecurityCode\""),RequestBody.create(null,SecurityCode)).addPart(Headers.of("Content-Disposition","form-data;name=\"File\";filename=\"avatar_upload.jpg\""),RequestBody.create(MediaType.parse("application/octet-stream"),file)).build();
这回Spring Boot multipart 依旧找不到文件信息了,这回的改动点是把mime类型由图片类型"image/jpeg"改成了附件类型:
"application/octet-stream"
最后借鉴StackOverFlow的某贴的代码:/questions/30707681/multipart-file-upload-with-okhttp-spring,
RequestBodybody=newMultipartBuilder().addFormDataPart("qqfile",filename,RequestBody.create(MediaType.parse("media/type"),newFile(filename))).type(MultipartBuilder.FORM).build();Requestrequest=newRequest.Builder().url("/path/to/your/upload").post(body).build();OkHttpClientclient=newOkHttpClient();Responseresponse=client.newCall(request).execute();
因为这个帖子的topic就是解决Spring MultiPart的问题,最后终于可以上传了,修改点在于彻底修改了添加文件使用的函数接口,我在build gradle里面已经准备用Apache HttpClient了。
OkHttp有点坑爹啊。
参考:
/square/okhttp/wiki/Recipes
/a/anzhuokaifa/androidkaifa//0824/3355.html