问题描述
在尝试将图像上传到我的服务时,我在Jersey和FormDataParam
的行为非常奇怪。我的服务在Dropwizard上运行。
接受图像(以及元数据对象)的方法如下:
@POST
@Path("/photos")
@Consumes("multipart/form-data")
fun upload(
@FormDataParam("photo") fileInputStream: FileInputStream,@FormDataParam("metadata") metadata: PhotoMetadataV1RequestModel
) {
// do something
}
我已经在Guice模块中注册了MultipartFeature
。
public class JerseyModule extends AbstractModule {
@Override
protected void configure() {
// other stuff
bind(MultiPartFeature.class).in(Scopes.SINGLETON);
}
}
我在jersey-multipart
中添加了build.gradle
依赖性。
// Jersey
compile "org.glassfish.jersey.core:jersey-server:$jerseyVersion"
compile "org.glassfish.jersey.media:jersey-media-multipart:$jerseyVersion"
现在有趣的部分。
如果我尝试使用绝对路径上传文件,这实际上有效!但是,它无法正常工作,我尝试使用相对路径上传文件。
更重要的是,当将服务部署到另一台计算机上时(它不是来自上载映像请求的),它也不起作用。这很重要,因为我将服务部署到了Heroku,并且需要从其他地方上传图像!
这是可行的(photo
的绝对路径):
curl --location --request POST "http://localhost:8095/rest/v1/self/photos" \
--header "Authorization: Bearer GaKC8xQju5h" \
--form 'photo=/Users/whizzil/Desktop/nova_scripts/create_users/user-lina/photos-webp/photo-profile-1.webp' \
--form 'metadata={"photoType": "PROFILE","position": 2};type=application/json'
但是,如果服务器的网址不是localhost,例如Heroku服务器。
这是行不通的(photo
的相对路径):
curl --location --request POST "http://localhost:8095/rest/v1/self/photos" \
--header "Authorization: Bearer GaKC8xQju5h" \
--form 'photo=@./photo-profile-1.webp' \
--form 'metadata={"photoType": "PROFILE","position": 2};type=application/json'
不起作用时抛出的异常:
org.glassfish.jersey.internal.inject.ExtractorException: org.glassfish.jersey.internal.inject.ExtractorException: java.io.FileNotFoundException: Invalid file path
org.glassfish.jersey.media.multipart.FormDataParamException: HTTP 400 Bad Request
at org.glassfish.jersey.media.multipart.internal.FormDataParamValueFactoryProvider$FormDataParamValueFactory.provide(FormDataParamValueFactoryProvider.java:352)
at org.glassfish.jersey.server.spi.internal.ParamValueFactoryWithSource.provide(ParamValueFactoryWithSource.java:71)
at org.glassfish.jersey.server.spi.internal.ParameterValueHelper.getParameterValues(ParameterValueHelper.java:90)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$AbstractMethodParamInvoker.getParamValues(JavaResourceMethodDispatcherProvider.java:127)
我在这里迷路了。我尝试使用Google搜索所有内容,但没有成功。任何帮助,不胜感激!
解决方法
将FileInputStream
更改为InputStream
解决了该问题。我不知道为什么。