How do i upload/stream large images using Spring 3.2 spring-mvc in a restful way

前端 未结 4 836
慢半拍i
慢半拍i 2020-12-13 19:48

I try to upload/stream a large image to a REST controller that takes the file and stores it in to a database.

@Controller
@RequestMapping(\"/api/member/pictu         


        
相关标签:
4条回答
  • 2020-12-13 20:02

    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.

    0 讨论(0)
  • 2020-12-13 20:07

    If you want do deal with the request body as an InputStream you can get it directly from the Request.

    @Controller
    @RequestMapping("/api/member/picture")
    public class MemberPictureResourceController {
    
        @RequestMapping(value = "", method = RequestMethod.POST)
        @ResponseStatus(HttpStatus.NO_CONTENT)
        public void addMemberPictureResource(HttpServletRequest request) {
            try {
                InputStream is = request.getInputStream();
                // Process and Store image in database
            } catch (IOException e) {
                // handle exception
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-13 20:08

    I have done this recently, see the details here.

    On the browser we can make use of the file API to load a file, then encode its contents using Base64 encoding, and finally assign the encoded contents to a javascript object before posting it.

    On the server, we have a Spring Controller which will handle the request. As part of the json unmarshalling that converts the the request body to a java object, the base64-encoded value for the image bytes will be converted to a standard Java byte[], and stored as a LOB in the database.

    To retrieve the image, another Spring Controller method can provide the image by streaming the bytes directly.

    The blog post I linked to above presumes you want to use the image as part of another object, but the principle should be the same if you want to only work with the image directly. Let me know if anything needs clarification.

    0 讨论(0)
  • 2020-12-13 20:24

    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.

    0 讨论(0)
提交回复
热议问题