使用multipart将图像保存到java项目路径

时间:2016-10-29 10:58:20

标签: java angularjs eclipse spring

尝试直接在项目路径中保存图像。图像直接从构建在Angularjs上的UI上传。我想将图像保存到一个文件夹中,在eclipse中的项目中却抛出异常。我正在使用Spring框架的MutipartFile接口

项目结构

web
|
 src
   |
    main
       |
        webapp
             |
              app
                |
                 images

代码

@RequestMapping(path = "/attachmentPath", method = RequestMethod.POST)
    public Response attachmentPath(Attachment attachment , @RequestParam(value = "file") MultipartFile file) throws IllegalStateException, IOException {
String orgName = file.getOriginalFilename();
String filePath = "/images/"+orgName;
        File dest = new File(filePath);
        try { file.transferTo(dest); }
        catch (IllegalStateException e) 
        { e.printStackTrace();}

异常

java.io.FileNotFoundException: img\images\users\TestCopy1.jpg (The system cannot find the path specified)

2 个答案:

答案 0 :(得分:1)

由于异常说time()变量未解析为完整的文件夹路径,因此您需要修复filePath变量以解析为完整的绝对路径网址(例如)。< / p>

Web应用程序文件夹绝对路径可以重试为filePath

request.getSession().getServletContext().getRealPath()

答案 1 :(得分:0)

您的 字符串 filePath = ...没有会话,也没有 ServletContext 。这会引发FileNotFoundException异常。 。

以下是我实施应用程序以直接在项目中保存文件的方法。您可以根据您的意愿更改路径(根目录)。

我的Pojo类产品:

public class Product implements Serializable{

...

@JsonIgnore 
    private MultipartFile  productImage;

//getters setters

@XmlTransient  
    public MultipartFile getProductImage() {
        return productImage;
    }

    public void setProductImage(MultipartFile productImage) {
        this.productImage = productImage;
    }
...

}

我的控制器

@RequestMapping(value = "/add", method = RequestMethod.POST)
    public String processAddNewProductForm(@ModelAttribute("newProduct") @Valid Product productToBeAdded, BindingResult result, HttpServletRequest request) {   

        MultipartFile productImage = productToBeAdded.getProductImage();
        String rootDirectory = request.getSession().getServletContext().getRealPath("/");

            if (productImage!=null && !productImage.isEmpty()) {
               try {

                productImage.transferTo(new File(rootDirectory+"resources\\images\\"+productToBeAdded.getProductId() + ".png"));
               } catch (Exception e) {
                throw new RuntimeException("Product Image saving failed", e);
           }
           }


       //   productService.addProduct(productToBeAdded); 
        return "redirect:/products";
    }