How to upload image to /src/main/webapp/Theme/img

2019-09-12 10:09发布

问题:

I am trying to upload a jpeg image to my spring module in /src/main/webapp/Theme/img folder.

Here is my test code:

 @RequestMapping(value="/uploadLogo", method=RequestMethod.POST)
        public ModelAndView uploadLogo(
                @RequestParam("file") MultipartFile file,Principal principal,HttpServletRequest request){
              ModelAndView model =null;
            if (!file.isEmpty()) {
                try {

                    byte[] bytes = file.getBytes();

                   String webappRoot = File.separator+"pl4sms";
        String relativeFolder = File.separator + "src"+ File.separator+"main"+ File.separator+"webapp" +  File.separator
                                 + "Theme2"+ File.separator+"img" +  File.separator;
        String filename = webappRoot + relativeFolder
                           + "1234.jpg";
                    BufferedOutputStream stream =
                            new BufferedOutputStream(new FileOutputStream(new File(filename)));
                    stream.write(bytes);
                    stream.close();





            } catch(Exception e){
                e.printStackTrace();
            }
            }else{
//              
            }
            return model;

        }

This gives me the following error:

java.io.FileNotFoundException: \pl4sms\src\main\webapp\Theme2\img\1234.jpg (The system cannot find the path specified)

Even if i try giving full path:

  BufferedOutputStream stream =
                new BufferedOutputStream(new FileOutputStream(new File("/pl4sms/src/main/webapp/Theme2/img/1234.jpg")));

Still it gives same error.

I have tried all options available on these links:

http://stackoverflow.com/questions/20720250/upload-image-to-folder-in-spring-mvc
http://stackoverflow.com/questions/25550875/how-to-upload-image-inside-webapp-folder
http://stackoverflow.com/questions/31515391/how-to-upload-image-file-to-spring-mvc-resource-folder

But nothing worked for me.

Please suggest me how to solve this issue

回答1:

This doesn't answer your question but a work around that i tired to fix the same problem.

You cannot upload files to your project folder. you can upload it to any other location. The solution i tried to fix the same problem is to create a folder whose location would be at the system homepath , i.e. :: i hosted my services on a ubuntu system therefore

(/home/ubuntu/yourFolderName)

give this folder permissions so that your code as access to this folder. Then write your files to this folder.