这是我在 Spring Boot 中上传图片的代码:
String root = ctx.getRealPath("/");
File dir = new File(root + File.separatorChar + "images");
if (!dir.exists())
dir.mkdir();
String path = dir.getAbsolutePath() + File.separatorChar
+ product.getProductName() + "."
+ file.getContentType().split("/")[1];
System.out.println(path);
File file1 = new File(path);
try {
FileOutputStream fod = new FileOutputStream(file1);
fod.write(file.getBytes());
fod.close();
product.setProductPicture("/images/" + product.getProductName()
+ "." + file.getContentType().split("/")[1]);
} catch (IOException e) {
e.printStackTrace();
}
文件上传工作正常,此代码的唯一问题是当我使用
ctx.getRealPath("/")
时它返回临时位置,当我重新启动 Spring Boot 应用程序时,我会丢失已经上传的现有文件,因为它会创建一个新的临时目录。这会导致一些问题,因为我还必须在我的网站上显示这些图片,现在它返回“找不到图像错误”。
所以我需要一个解决方案,它允许我在一个永久位置上传文件并从那里在浏览器上提供文件。
注:我正在使用 thymeleaf 进行查看。
最佳答案
我找到了解决我的问题的方法。我创建了一个新函数,它只会返回 bytes[]
并作为响应正文发送,如下所示:
@RequestMapping(value = "image/{imageName}")
@ResponseBody
public byte[] getImage(@PathVariable(value = "imageName") String imageName) throws IOException {
File serverFile = new File("/home/user/uploads/" + imageName + ".jpg");
return Files.readAllBytes(serverFile.toPath());
}
并在 html
<img alt="Image" th:src="@{image/userprofile}" width="250" height="250"/>
关于spring-mvc - 使用 thymeleaf 和 spring boot 上传和显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41083751/