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

后端 未结 1 1747
一向
一向 2021-01-27 10:54

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:

         


        
相关标签:
1条回答
  • 2021-01-27 11:26

    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>
    
    0 讨论(0)
提交回复
热议问题