简体   繁体   中英

405 Error : multipart/form-data with Spring

I am trying to send a Json string along with multiple files into my Spring Controller, however it would always give me a 405 Method Not Allowed Error, what am I doing wrong?

Javascript Code:


var formdata = new FormData();
formdata.append('user', JSON.stringify(userData));

files.forEach(file=> {
  formdata.append('files', file);
});

jQuery.ajax({
    url: "user/submitForm",
    type: "POST",
    data: formdata,
    enctype: 'multipart/form-data',
    processData: false,
    contentType: false,
    success: function (data)
    {
        console.log("SUCCESS");
    },
    error: function (request, status, error) {
        alert(status + " : " + JSON.stringify(request));
    }
});

Controller in Spring:

@PostMapping(value= "/submitForm", consumes = { 
                        MediaType.APPLICATION_JSON_VALUE, 
                        MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<?> userRegistration( @RequestPart("user") String user,
            @RequestPart("files") List<MultipartFile> files, BindingResult bindingResult) {
        
        ObjectMapper obj = new ObjectMapper();
        User newUser = new User();
        newUser = obj.readValue(user, User.class);
        
        System.out.println("User : \n"+ newUser.toString());
        System.out.println("Files : \n"+ files.toString());
        return null;
}

This was the solution that I found from Antonio112009's answer

SOLUTION

@PostMapping(value = "/submitForm")
public ResponseEntity<?> userRegistration(
            @RequestParam("user") String user,
            @RequestParam(value = "files", required = false) List<MultipartFile> files) {

        ObjectMapper obj = new ObjectMapper();
        User user = new User();
        .
        .
        .
}
    

I use another solution, who works as expected and are a bit more flexible from my point of view.

Front-end part is in Typescript.

Front-end

var formData = new FormData();
options.files.forEach(function (file) {
    formData.append(file.name, file);
});
formData.append("myParam", "coucou");
var xhr = new XMLHttpRequest();
xhr.open("POST", "/rest/upload");
xhr.onload = function () {
    var data = JSON.parse(xhr.responseText);
    options.callback("success", options.files.map(function (file) {
        return {
            file: file,
            content: data[file.name]
        };
    }));
}; 
xhr.send(formData);

Back-end (Java Spring)

@RestController
@RequestMapping(value = "/rest")
public class UploadController {
    
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<Boolean> upload(MultipartHttpServletRequest request) {
        // Get param
        Object myParam = request.getParameter("myParam");
        // Get iteretaor on all files
        Iterator<String> iterator = request.getFileNames();
        MultipartFile multipartFile = null;
        while (iterator.hasNext()) {
            multipartFile = request.getFile(iterator.next());
            final String fileName = multipartFile.getOriginalFilename();
            final String fileSize = String.valueOf(multipartFile.getSize());
            // Add logic ....      
        }      
    }
    return new ResponseEntity(true);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM