我在编写控制器时出现问题,以便将照片上传到服务器.
控制器
@RequestMapPing(value = "photos", method = RequestMethod.POST)@ResponseBodypublic Response uploadPhoto(@RequestPart PhotoMetaData data, @RequestParam String localname, @RequestPart(required = false) multipartfile file, httpServletRequest request) { log.info("@uploadPhoto > ip of request: " + request.getRemoteAddr() + ", MetaData: " + data); return photosService.storePhoto(data, file, localname);}
问题是文件是null但是在检查请求参数时,请求显然有3个多部分参数,每个都有它假设的ContentType但文件是一个长字符串.
AndroID应用程序正在调用此代码.我正在使用Okhttp来构建多部分请求.码:
MediaType JsonMediaType = MediaType.parse("application/Json");Requestbody requestbody = new MultipartBuilder() .type(MultipartBuilder.FORM) .addPart(headers.of("Content-disposition", "form-data; name=\"data\""), Requestbody.create(JsonMediaType, photoMetaDataStr)) .addPart(headers.of("Content-disposition", "form-data; name=\"localname\""), Requestbody.create(MediaType.parse("text/plain"), localname.getPath())) .addPart(headers.of("Content-disposition", "form-data; name=\"file\""), Requestbody.create(MediaType.parse("image/jpeg"), new file(localname.getPath()))) .build(); Request request = new Request.Builder().url(url).post(requestbody).build(); final Response response = clIEnt.newCall(request) .execute();
——编辑————
相关豆类:
@Beanpublic MultipartResolver multipartResolver() { return new CommonsMultipartResolver();}
—-编辑2 —–
更改控制器签名后,需要该文件我得到一个例外:
—-编辑3 ——
经过大量测试后,我注意到问题可能就是我使用okhttp将多部分请求发送到服务器的方式.使用Postman客户端,呼叫成功
error with request org.springframework.web.multipart.support.DefaultMultiparthttpServletRequest@3d854606org.springframework.web.multipart.support.MissingServletRequestPartException: required request part 'file' is not present.
谢谢你的时间和帮助
罗伊
解决方法:
我只能通过向请求添加Content-transfer-encoding标头来解决问题.
Requestbody requestbody = new MultipartBuilder().type(MultipartBuilder.FORM) .addPart(headers.of("Content-disposition", "form-data; name=\"data\""), Requestbody.create(JsonMediaType, GsonInstance.getInstance() .toJson(photoMetaData))) .addPart(headers.of("Content-disposition", "form-data; name=\"file\"; filename=\"localname\"", "Content-transfer-encoding", "binary"), Requestbody.create(MediaType.parse("image/jpeg"), new file(localname.getPath()))) .build();
我不确定为什么会这么重要.据我所知,当ContentType是image时,默认传输编码是二进制的.也许这是okhttp的一个小错误?
总结以上是内存溢出为你收集整理的android – Multipart请求spring不绑定文件数据全部内容,希望文章能够帮你解决android – Multipart请求spring不绑定文件数据所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)