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

后端 未结 1 1748
一向
一向 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: 
    
    
        File2 to upload: 
    
        Name2: 
    
    
         Press here to upload the file!
    
    

    0 讨论(0)
提交回复
热议问题