【问题标题】:Image not uploading in spring mvc图片未在spring mvc中上传
【发布时间】:2017-01-01 20:51:38
【问题描述】:

我正在开发一个 Spring MVC 应用程序。 其中正在将图像上传到 WEB-INF\resources\imgages folder ,但图像未添加到文件夹中。

在控制台中显示

具有原始文件名 [Penguins.jpg] 的多部分文件“imageFile”, 存储在 [D:\Clickindians_Web.metadata.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\Click-Indians\upload__3b6778cf_156c1787f2b__7ffd_00000012.tmp]: 搬去 [D:\Clickindians_Web.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Click_Indians\WEB-INF\resources\images\Penguins.jpg]

我的代码是:

@RequestPart(value = "imageFile", required = false) MultipartFile file,
            HttpServletRequest request) {

     if (!file.isEmpty()) {
         try {

             String rootDirectory = request.getSession().getServletContext().getRealPath("/");
        path= Paths.get(rootDirectory+"\\WEB-INF\\resources\\images\\");


             String orgName = file.getOriginalFilename();
             String filePath = path + "\\"+orgName;
             File dest = new File(filePath);
             file.transferTo(dest);
         }catch(Exception ex){

            ex.printStackTrace();
            throw new RuntimeException("Product Image saved failed",ex);

        }
     }

我想在实时服务器上托管这个应用程序..

【问题讨论】:

  • Here 是如何在 Spring 中上传文件的绝佳示例。
  • 为什么要把图片保存在那里?下次部署应用程序时,您将丢失它们。您所附的图像也不能证明任何事情。如果在 IDE 之外添加了文件,则需要在 Eclipse 中刷新文件夹。
  • 那么如何在我的应用程序之外存储图像,你能给出一个工作示例代码吗?

标签: java eclipse spring spring-mvc


【解决方案1】:

这里有一个关于我如何使用 Spring 的小例子。它是 Groovy,但只需将变量声明为其类型即可轻松转换为 Java。

@PostMapping("/upload")
def upload(@ModelAttribute("file") MultipartFile file) {
    def fullPath = "/some/path/" + file.originalFilename

    def outputFile = new File(fullPath)
    outputFile.mkdirs()

    def bis = new ByteArrayInputStream(file.bytes)
    def original = ImageIO.read(bis)
    ImageIO.write(original, "PNG", outputFile)
}

【讨论】:

  • 使用您的代码我可以将图像上传到我的本地驱动器,但它不适用于将图像上传到 webapp 文件夹。
  • 当然,正如 Alan Hay 所说,这是一个糟糕的主意。您将在下次部署时丢失该文件夹。您应该在整个部署环境之外选择一个文件夹。
  • 你好 Trojahn 你能给出一个在 Myapp 之外存储图像的示例代码吗?
猜你喜欢
  • 2014-12-04
  • 2017-12-15
  • 2012-12-02
  • 1970-01-01
  • 2021-08-27
  • 2020-09-26
  • 2016-04-20
  • 1970-01-01
  • 2022-12-17
相关资源
最近更新 更多