[英]How to upload files in resources folder in spring rest
I have a folder inside resources folder where I want to upload media files. 我在资源文件夹中有一个要上传媒体文件的文件夹。 But I am constantly getting 'No file or directory found' error. 但是我不断收到“找不到文件或目录”错误。
Here is what I have in my controller 这是我控制器中的物品
@Autowired
ServletContext servletContext;
@RequestMapping(value = "/uploads", method = RequestMethod.POST)
public String insert(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
// String path = new
// ClassPathResource("/src/main/resources/uploads").getPath();
// FileCopyUtils.copy(file.getBytes(), new File(path));
String webappRoot = servletContext.getRealPath("/");
String relativeFolder = File.separator + "resources" + File.separator + "uploads" + File.separator;
System.out.println(webappRoot);
System.out.println(relativeFolder);
String filename = webappRoot + relativeFolder + file.getOriginalFilename();
FileCopyUtils.copy(file.getBytes(), new File(filename));
return "uploaded successfully";
}
And here is the error I am getting constantly 这是我不断得到的错误
SEVERE: Servlet.service() for servlet [api] in context with path [/ek-service] threw exception
java.io.FileNotFoundException: /home/ekbana/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ek-service/resources/uploads/2.jpg (No such file or directory)
I have searched all over the web tried ResourceLoader and ClassPath. 我在网上搜索了所有尝试过的ResourceLoader和ClassPath。 But still no success figuring it out. 但是,仍然无法成功解决它。
Resources should be considered read-only, they are not accessible through the file system, but are embedded in the war/jar when you deploy an application. 资源应被视为只读资源,无法通过文件系统访问,但在部署应用程序时将资源嵌入到war / jar中。
You must write the file to a path on the file system that exists and that your application has write access to. 您必须将文件写入存在的文件系统上,并且应用程序具有写访问权的路径。
You can write to a temporary file, it has the benefit that you most certainly will have write access to it. 您可以写入一个临时文件,它的好处是您肯定会对该文件具有写权限。 Useful for testing until you figure out a permanent location to store the file, or for cases when permanent storage is not necessary. 在您确定存储文件的永久位置之前进行测试时很有用,或者在不需要永久存储的情况下进行测试。 See example: http://www.mkyong.com/java/how-to-create-temporary-file-in-java/ 参见示例: http : //www.mkyong.com/java/how-to-create-temporary-file-in-java/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.