图像无法在春季mvc上传

时间:2016-08-25 12:12:22

标签: java eclipse spring spring-mvc

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

enter image description here

在控制台中显示

  

原始文件名为[Penguins.jpg]的多部分文件'imageFile',   存储在   [d:\ Clickindians_Web.metadata.plugins \ org.eclipse.wst.server.core \ TMP0 \工作\卡塔利娜\本地主机\点击印度人\ upload__3b6778cf_156c1787f2b__7ffd_00000012.tmp]:   搬去   [d:\ Clickindians_Web.metadata.plugins \ org.eclipse.wst.server.core \ TMP0 \ wtpwebapps \ Click_Indians \ WEB-INF \资源\图像\ 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);

        }
     }

我想在实时服务器中托管此应用..

1 个答案:

答案 0 :(得分:0)

这是一个关于我如何使用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)
}