Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

im working on a spring mvc project . i want to upload image and save it to resources/img/folder.

I tried below code but it does not save the image to the directory.

@Autowired
    private HttpServletRequest request;
    try {
            // MultipartFile file = uploadItem.getFileData();
            String fileName = null;
            InputStream inputStream = null;
            OutputStream outputStream = null;
            if (multipartFile.getSize() > 0) {
                inputStream = multipartFile.getInputStream();

                System.out.println("File Size:::" + multipartFile.getSize());

                fileName = request.getSession().getServletContext().getRealPath("/resources/") + "/students/"
                        + multipartFile.getOriginalFilename();
                outputStream = new FileOutputStream(fileName);
                System.out.println("OriginalFilename:" + multipartFile.getOriginalFilename());
                System.out.println("fileName----"+fileName);
                int readBytes = 0;
                byte[] buffer = new byte[10000];
                while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
                    outputStream.write(buffer, 0, readBytes);
                }
                outputStream.close();
                inputStream.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

Exception

11:00:39,436 INFO  [stdout] (http--0.0.0.0-8080-5) File Size:::7346
11:00:39,436 ERROR [stderr] (http--0.0.0.0-8080-5) java.io.FileNotFoundException
: C:jboss-as-7.1.1.Finalstandalone	mpvfsdeployment65ea7dd580659db3ObviousR
esponseWeb-1.2-SNAPSHOT.war-3a7509e73dad1cba
esourcesstudentszzzz.jpg (The sy
stem cannot find the path specified)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
209 views
Welcome To Ask or Share your Answers For Others

1 Answer

   String saveDirectory=request.getSession().getServletContext().getRealPath("/")+"images";//to save to images folder
   String fileName = multipartFile.getOriginalFilename();//getting file name
   System.out.println("directory with file name: " + saveDirectory+fileName);
   multipartFile.transferTo(new File(saveDirectory + fileName));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...