File upload won't work with angular-file-upload and Spring
Asked Answered
M

1

0

I am trying to make a simple file upload possible but Spring does not want to play with me.

This is the endpoint for file uploads - currently not doing a lot:

@PostMapping(WordEmbeddingApiPaths.UPLOAD_MODEL)
@RequestMapping(method=RequestMethod.POST, consumes = {"multipart/form-data"})
public ResponseEntity<WordVectorListDto> uploadModel(
        @ModelAttribute("file") MultipartFile file,
        // @RequestBody Object obj,
        RedirectAttributes redirectAttributes) {

    LOGGER.debug("POST uploadModel");

    return new ResponseEntity<WordVectorListDto>((WordVectorListDto)null, HttpStatus.OK); 
}

I've tried several things but it all ends up in different errors. I've just tried to use @RequestBody because I thought maybe that's the trick but then I get an exception saying:

Content type 'multipart/form-data;boundary=----WebKitFormBoundarycV8dFSvDV6U9OwJq' not supported

or

Content type 'multipart/form-data' not supported

depending on what I just tried.

If I go with @RequestPart("file") MultipartFile file I see

Required request part 'file' is not present

which is similar for @RequestParam("file").

I have no idea what's so hard on this but I hope somebody can tell me how I can get that file from the client.

Below you can see the request I've sent to the endpoint:

Is this request okay?

enter image description here


Web Client:

var uploader = $scope.uploader = new FileUploader({
    url: 'http://localhost:8080/rest-api/dl4j/we/uploadModel'
});

uploader.onAfterAddingFile = function($modelFile) {

    console.info('onAfterAddingFile', $modelFile);

    var fd = new FormData();        
    fd.append('file', $modelFile.file);

    $http.post($modelFile.url, fd, {
        headers: {
            'Content-Type': undefined
        },
        transformRequest: angular.identity          
    })
    .then(
        function (data) {
            alert("upload success");
        }, 
        function (data, status) {
            alert("upload error");
        }
     );
};  

index.html

<label class="btn btn-default btn-file" style="float:right;">
    Upload 
    <input 
        type="file" 
        style="display: none;"
        name="file"     
        multiple    
        nv-file-select                  
        uploader="uploader">
</label>
Maisel answered 4/2, 2017 at 19:25 Comment(1)
Possible duplicate of File upload won't work with angular-file-upload and Spring.Simmers
Z
1

Here is how i didi it:

 @RequestMapping(value="/uploadFile", method=RequestMethod.POST)
            public @ResponseBody String handleFileUpload(
                    @RequestParam("file") MultipartFile file){
                String name = "test11";
                if (!file.isEmpty()) {
                    try {
                        byte[] bytes = file.getBytes();
                        BufferedOutputStream stream =
                                new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));
                        stream.write(bytes);
                        stream.close();
                        return "You successfully uploaded " + name + " into " + name + "-uploaded !";
                    } catch (Exception e) {
                        return "You failed to upload " + name + " => " + e.getMessage();
                    }
                } else {
                    return "You failed to upload " + name + " because the file was empty.";
                }
            }

and dont forget to register the multipart resolver:

@Bean
public MultipartResolver multipartResolver() {
    org.springframework.web.multipart.commons.CommonsMultipartResolver multipartResolver = new org.springframework.web.multipart.commons.CommonsMultipartResolver();
    multipartResolver.setMaxUploadSize(10000000);
    return multipartResolver;
}

here is the html code ... take a look at the name/id of the input fields .. File1 to upload:

    Name1: <input type="text" name="name">


    File2 to upload: <input type="file" name="file">

    Name2: <input type="text" name="name">


    <input type="submit" value="Upload"> Press here to upload the file!
</form>
Zelmazelten answered 4/2, 2017 at 19:40 Comment(8)
@RequestParam("file") does not work because Spring keeps telling me the parameter was missing.Maisel
I ve updated my anwser ... take a look at the html code ...... name of input type file is ... fileZelmazelten
Well, I have it similar and from the screenshot I think the parameter has been set correctly.Maisel
Ok, not sure but in the screenshot you have @RequestHeaders Contentype:multipart/form-data; boundary=-----WebKitFormBoundary I Think the boundary=-----WebKitBoundary does not belong there.... do you have an ideqa where it comes from?Zelmazelten
I am not sure, I am not sure where this comes from but it might come from angular's file upload. However, I've added the JavaScript and HTML parts from the client to my question.Maisel
i can only guess ... headers: { 'Content-Type': undefined }Zelmazelten
No, that can't be the issue. The header is getting set as can be seen from the actual request that is being sent - one has to set it to undefined - I know that looks strange but yeah ..Maisel
Remove consumes = {"multipart/form-data"} in handler and try. input content type doesnt match with the content type defined in consumes fieldDonnie

© 2022 - 2024 — McMap. All rights reserved.