Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

java - How to upload image file to spring mvc resource folder

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

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

1 Reply

0 votes
by (71.8m points)
   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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...