我在资源文件夹中有一个文件夹,我想在其中上传媒体文件。但我不断收到“找不到文件或目录”错误。
这是我 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";
}
这是我经常遇到的错误
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)
我在网上搜索过ResourceLoader和ClassPath。但仍然没有成功弄清楚。
最佳答案
资源应被视为只读,它们无法通过文件系统访问,但在部署应用程序时嵌入到 war/jar 中。
您必须将文件写入文件系统上存在且您的应用程序具有写入权限的路径。
您可以写入临时文件,它的好处是您肯定可以对其进行写入访问。对于测试很有用,直到您找到存储文件的永久位置,或者在不需要永久存储的情况下。参见示例:http://www.mkyong.com/java/how-to-create-temporary-file-in-java/
关于java - 如何在Spring Rest中上传资源文件夹中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36981703/