How do I upload file, which content comes as request param in Spring MVC

3.8k views Asked by At

I use crop utility to resize pictures and it transform image data as Base64 String.

    -----------------------------27138656916051
Content-Disposition: form-data; name="typePhoto"

string
-----------------------------27138656916051
Content-Disposition: form-data; name="imageData"

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAfZ0lEQVR4nO2deXAUZfrHn1xkwgyRBEi4hbjAci4gp4gIhAWKy3IXLFgwBYKAEeVeCCvrz4NlAZFFYEPA4JLIJQoChiMi54olhENANOEK1wKGM5AIOb6
/P1Ld9sz09Ez3+04I8HyqupLp6X6et3v6M9PHexAYhvEIPegCMExZhgVhGANYEIYxgAVhGANYEIYxgAVhGANYEIYxgAVhGANYEIYxgAVhGANKVZAuXbrAbrd7nMLDwxEVFYWGDRviL3
/5C/Lz8y3l6dGjh2EeXyYzhIWFwW63o3z58pbKq9CvX.....bytes

When I get

@RequestParam(value = "imageData") String data \\"data:image/png;base64,iVBORw0KGgoA....bytes"

I have already implementation of file upload as Multipart File to store it in file system. And is it possible to convert bytes decoded from request parametre to MultipartFile?

1

There are 1 answers

2
We are Borg On

In you ApplicationContext.xml, you will need to add this :

<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <beans:property name="maxUploadSize" value="52428800"/>
    </beans:bean>

Then you would require a Controller method something like this :

  @RequestMapping(value = "/addattachment", method = RequestMethod.POST)
    public
    @ResponseBody
    String addAttachments(@RequestParam("attachments") MultipartFile[] multipartFiles) {

        if (multipartFiles != null && multipartFiles.length > 0) {
            for (MultipartFile multipartFile : multipartFiles) {
                try {
                    if (!(multipartFile.isEmpty())) {
                        String fileName = multipartFile.getOriginalFilename();
                        long fileSize = multipartFile.getSize();
                        byte[] bytes = multipartFile.getBytes();
                         // Call the save to DB or disk here.
                       }
                } catch (Exception e) {
                    return "failure";
                }
            }
        }
        return "done";
    }

If you need any help, lemme know.

Also, i just read, that you want to send image, then your controller method should look like this :

  @RequestMapping(value = "/addimage", method = RequestMethod.POST)
    public @ResponseBody String convertimagetopdf(@RequestBody String imagedat) {
//do stuff with image
}