How do i upload/stream large images using Spring 3.2 spring-mvc in a restful way
As it looks as if you are using spring you could use HttpEntity ( http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/http/HttpEntity.html ).
Using it, you get something like this (look at the 'payload' thing):
@Controller
public class ImageServerEndpoint extends AbstractEndpoint {
@Autowired private ImageMetadataFactory metaDataFactory;
@Autowired private FileService fileService;
@RequestMapping(value="/product/{spn}/image", method=RequestMethod.PUT)
public ModelAndView handleImageUpload(
@PathVariable("spn") String spn,
HttpEntity<byte[]> requestEntity,
HttpServletResponse response) throws IOException {
byte[] payload = requestEntity.getBody();
HttpHeaders headers = requestEntity.getHeaders();
try {
ProductImageMetadata metaData = metaDataFactory.newSpnInstance(spn, headers);
fileService.store(metaData, payload);
response.setStatus(HttpStatus.NO_CONTENT.value());
return null;
} catch (IOException ex) {
return internalServerError(response);
} catch (IllegalArgumentException ex) {
return badRequest(response, "Content-Type missing or unknown.");
}
}
We're using PUT here because it's a RESTfull "put an image to a product". 'spn' is the products number, the imagename is created by fileService.store(). Of course you could also POST the image to create the image resource.
When you send a POST request, there are two type of encoding you can use to send the form/parameters/files to the server, i.e. application/x-www-form-urlencoded
and multipart/form-data
. Here is for more reading.
Using application/x-www-form-urlencoded
is not a good idea if you have a large content in your POST request because it usually crashes the web browser (from my experience). Thus,
multipart/form-data
is recommended.
Spring can handle multipart/form-data
content automatically if you add a multipart resolver to your dispatcher. Spring's implementation for handling this is done using apache-commons-fileupload so you will need to add this library to your project.
Now for the main answer of how to actually do it is already been blogged here http://viralpatel.net/blogs/spring-mvc-multiple-file-upload-example/
I hope that might help you to find a solution. You may want to read up about what REST is. It sounds like you are a bit confused. Basically, almost all http requests are RESTful even if the urls are ugly.