问题
I have tried a large number of examples for doing file upload with jersey. I can get it to work with pure Spring using @RequestMapping, ResponseEntity instead of @Path etc. But I want to use jersey, as all of my other endpoints are handled by jersey.
UPDATE: I feel that I'm unable to pass an form data, file or text. Even a single FormDataParam of @FormDataParam("directory") String directory gives the bad request
I have the following class
@Component
@Path("/v1.0")
public class FileOperationsResource {
private ConfigurationReader mConfigReader;
@Autowired
public FileOperationsResource(ConfigurationReader configurationReader) {
mConfigReader = configurationReader;
}
@POST
@Path("/file/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(@QueryParam("dir") String directory,
@FormDataParam("file") InputStream file,
@FormDataParam("file") FormDataContentDisposition fileDisposition) {
I have added the following line to my ResourceConfig
register(MultiPartFeature.class);
I have added the following maven dependency, but have not added a version as my understanding is that it will automatically pull the version that works with my version of spring, and I have found newer versions no longer allow me to add register in ResourceConfig as MultiPartFeature is missing.
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
</dependency>
When I make the following call, I get a 400 Bad Request. I feel like I must be making the call wrong, or have failed to wire something else in. Any help would be appreciated.
Response:
{
"timestamp": "2018-04-20T15:51:01.790+0000",
"status": 400,
"error": "Bad Request",
"message": "Bad Request",
"path": "/api/v1.0/file/upload"
}
I've made the call with Postman and using forms, as well as curl with the following call
curl --verbose --form file=@"settings.xml" http://localhost:8080/api/v1.0/file/upload?dir=MyDir
回答1:
What is your spring.jersey.type set to in application.properties? I have file upload working with Jersey and Boot, I believe this is what you need:
# JERSEY
spring.jersey.type=servlet
spring.jersey.servlet.load-on-startup=1
For example purposes, here's my endpoint:
@POST
@Path("/file/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition fileDisposition) {
String fileName = fileDisposition.getFileName();
StringBuilder fileContents = new StringBuilder();
int read = 0;
int totalBytesRead = 0;
byte[] bytes = new byte[1024];
try {
while ((read = fileInputStream.read(bytes)) != -1) {
...save file...
}
} catch (IOException e) {
mLogger.error(e.getMessage(), e);
}
return Response.ok().build();
}
来源:https://stackoverflow.com/questions/49945648/using-jersey-in-spring-boot-for-file-upload-getting-400-bad-request