小编Aks*_*hav的帖子

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

这是我在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("/")它返回临时位置,当我重新启动弹簧启动应用程序时,我已经上传已经上传的文件,因为它创建了一个新的临时目录.

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

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

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

file-upload spring-mvc thymeleaf spring-boot

4
推荐指数
1
解决办法
8720
查看次数

标签 统计

file-upload ×1

spring-boot ×1

spring-mvc ×1

thymeleaf ×1