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

时间:2022-01-24 21:21:36

Trying to save image in project path directly. Image is directly uploading from UI which is build on Angularjs. I want to save the image to a folder, in the project in eclipse but it is throwing exception. I am using MutipartFile interface of spring framework

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

Project Structure

web
|
 src
   |
    main
       |
        webapp
             |
              app
                |
                 images

Code

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

Exception

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

2 个解决方案

#1


1  

As the exception says filePath variable is NOT resolved to a complete folder path, so you need to fix your filePath variable to resolve to a complete absolute path url like below (for example).

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

The web application folder absolute path can be retrived as request.getSession().getServletContext().getRealPath()

Web应用程序文件夹绝对路径可以作为request.getSession()。getServletContext()。getRealPath()重试

@RequestMapping(path = "/attachmentPath", method = RequestMethod.POST)
public Response attachmentPath(HttpServletRequest request, Attachment attachment , @RequestParam(value = "file") MultipartFile file) throws IllegalStateException, IOException {
    String orgName = file.getOriginalFilename();
    String absolutePathToImages = request.getSession().getServletContext().getRealPath("/images/");
    String filePath = absolutePathToImages + orgName;
    File dest = new File(filePath);
    //check destination exists, if not create it
    if(!dest.exists())
    {
       new File(dest).mkdir();
    }
    try { 
       file.transferTo(dest); 
    }
    catch (IllegalStateException e) 
    { 
        e.printStackTrace();
    }

#2


0  

Your String filePath = ... has no session nor ServletContext . This is throwing the FileNotFoundException exception. .

你的String filePath = ...没有session或ServletContext。这是抛出FileNotFoundException异常。 。

Here is how I implemented my app to save the file directly in the project. You can change the path (root directory) according to your accordingingly.

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

My Pojo class Product:

我的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;
    }
...

}

My controller

@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";
    }

#1


1  

As the exception says filePath variable is NOT resolved to a complete folder path, so you need to fix your filePath variable to resolve to a complete absolute path url like below (for example).

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

The web application folder absolute path can be retrived as request.getSession().getServletContext().getRealPath()

Web应用程序文件夹绝对路径可以作为request.getSession()。getServletContext()。getRealPath()重试

@RequestMapping(path = "/attachmentPath", method = RequestMethod.POST)
public Response attachmentPath(HttpServletRequest request, Attachment attachment , @RequestParam(value = "file") MultipartFile file) throws IllegalStateException, IOException {
    String orgName = file.getOriginalFilename();
    String absolutePathToImages = request.getSession().getServletContext().getRealPath("/images/");
    String filePath = absolutePathToImages + orgName;
    File dest = new File(filePath);
    //check destination exists, if not create it
    if(!dest.exists())
    {
       new File(dest).mkdir();
    }
    try { 
       file.transferTo(dest); 
    }
    catch (IllegalStateException e) 
    { 
        e.printStackTrace();
    }

#2


0  

Your String filePath = ... has no session nor ServletContext . This is throwing the FileNotFoundException exception. .

你的String filePath = ...没有session或ServletContext。这是抛出FileNotFoundException异常。 。

Here is how I implemented my app to save the file directly in the project. You can change the path (root directory) according to your accordingingly.

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

My Pojo class Product:

我的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;
    }
...

}

My controller

@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";
    }