File upload won't work with angular-file-uploa

2019-03-06 16:46发布

问题:

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?


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>

回答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>