尝试直接在项目路径中保存图像。图像直接从构建在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)
答案 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";
}