【问题标题】:How to upload image file to spring mvc resource folder如何将图像文件上传到spring mvc资源文件夹
【发布时间】:2015-07-20 11:31:42
【问题描述】:

我正在开发一个 spring mvc 项目。我想上传图片并将其保存到资源/img/文件夹。

我尝试了下面的代码,但它没有将图像保存到目录中。

@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();
        }

例外

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.Final\standalone\tmp\vfs\deployment65ea7dd580659db3\ObviousR
esponseWeb-1.2-SNAPSHOT.war-3a7509e73dad1cba\resources\students\zzzz.jpg (The sy
stem cannot find the path specified)

【问题讨论】:

  • 您在日志中看到什么错误/异常?
  • 服务器控制台上没有显示错误。
  • okies.. 你能在每个 LOC 之后添加更多调试语句并分享它们吗?
  • 我有这些代码,但仍然没有异常尝试 { multipartFile.transferTo(resourceLoader.getResource("resources/css/"+multipartFile.getOriginalFilename()).getFile()); } catch (IllegalStateException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); }
  • 我的意思是将调试日志放在方法入口处,然后在 if 之前和之后(带有评估值)等等。这将帮助我们获得更多信息以将确切问题归零

标签: java spring spring-mvc


【解决方案1】:
   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));

【讨论】:

  • 此代码会将图像上传到 webapp/resources/images 目录。我不知道spring。通过在这里猜测,我给出了这个代码。
  • 所以用 sys.out ststmnt 检查路径。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 2014-05-02
  • 1970-01-01
  • 1970-01-01
  • 2020-11-12
  • 1970-01-01
  • 2020-01-10
相关资源
最近更新 更多