使用thymeleaf和springboot上传和显示图像

Aks*_*hav 4 file-upload spring-mvc thymeleaf spring-boot

这是我在Spring启动时上传的图片代码.

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();
}
Run Code Online (Sandbox Code Playgroud)

上传文件工作正常,只有这个代码的问题是,当我使用ctx.getRealPath("/")它返回临时位置,当我重新启动弹簧启动应用程序时,我已经上传已经上传的文件,因为它创建了一个新的临时目录.

这会导致一些问题,因为我还必须在我的网站上显示此图片,现在它返回"图像未找到错误"

所以我需要一个解决方案,允许我在永久位置上传文件,并在浏览器上提供文件.

注意:我正在使用百里香来观看

Aks*_*hav 5

我找到了解决问题的方法.我创建了一个新函数,它只返回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());
}
Run Code Online (Sandbox Code Playgroud)

并在HTML中 <img alt="Image" th:src="@{image/userprofile}" width="250" height="250"/>