spring boot web项目 图片文件的存取

对于图片在web应用中的存储,有两种解决方案

  1. 传入数据库,直接使用数据库的增删改查进行对图片的存储以及读取
  2. 传入服务器(主机)的某个磁盘,使用映射进行读取文件

我选择的是第二种因为第一种对于少量的图片进行存储尚还可以,但是图片量如果变多,那么数据库中的信息就会变得臃肿.

顺序:

  1. 前端传入图片信息
  2. 后端使用对应的文件类型进行接收文件,处理文件(保存),我这边需要回显就直接返回了这个图片的url
  3. 转到另一个页面,通过返回的传递url给这个页面,我这里返回的是list集合,可以看到所有保存的图片(需要将本地文件夹绑定到指定url,以此确保能够成功访问)

简单示例

<!-- 提交页面 -->
<form th:action="@{/img}" method="post" enctype="multipart/form-data">
    图片:<input type="file" name="imgFile"/>
    <button type="submit">提交</button>
</form>

<!-- 展示页面 -->
<table>
    <tr th:each="url:${urls}">
        <td>
            <img th:src="@{${url}}"/>
        </td>
    </tr>
</table>
//存储工具类
public class ImgUtils {
    //获得系统的图片地址,获得图片地址handler 保存后进行传回url ,你可以直接指定值
    @Value("${file.img.path.handler}")
    public String imgWebPath;
    @Value("${file.img.path}")
    public String imgRealPath;
    
    // 上面通过配置文件指定了图片文件在服务器(主机)上存储的位置
    /*
    	file.img.path=D:/workspace/onlineshop20200704/target/classes/img/
		file.img.path.handler=/file/img/**
	*/

    public Result saveWebImg(MultipartFile imgFile){
        // 1.初始化变量
        File destFile = null;
        String webImgPath = null;
        try {
            //2.根据时间戳创建新的文件名,避免文件名重复出现错误.
            String fileName = System.currentTimeMillis() + getSuffix(imgFile.getOriginalFilename());
            //3.获得路径,然后拼接前面的文件名
            String destFileName = imgRealPath + fileName;
            //4.第一次运行的时候,这个文件所在的目录往往是不存在的,这里自动创建指定文件夹
            destFile = new File(destFileName);
            destFile.getParentFile().mkdirs();
            //5.把浏览器上传的文件复制到本地的位置
            imgFile.transferTo(destFile);
            //6.获取服务器名
            webImgPath = new String(imgWebPath);
            webImgPath = webImgPath.replace("**",fileName);
//            m.addAttribute("fileName", fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("上传失败," + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("上传失败," + e.getMessage());

        }
		// 这里封装了一个result,我将url信息存在里面,工程需要,不必深究
        return ResultGenerator.genSuccessResult().setMessage(webImgPath);
    }

    private String getSuffix(String fileName){
        int lastIndexOf = fileName.lastIndexOf(".");
        String suffix = fileName.substring(lastIndexOf);
        return suffix;
    }
@Controller
public class ImgController {
    @Autowired
    private ImgUtils imgUtils;

    public static List<String> urls = new ArrayList<String>();

    @RequestMapping("/goImg")
    public String ImgPage(){
        return "test/img";
    }

    @RequestMapping("/img")
    public String getImg(MultipartFile imgFile){
        Result result = imgUtils.saveWebImg(imgFile);

        if (result.getCode()==200){
            //保存成功
            System.out.println("success:"+result.getMessage());
            // 直接添加在静态list中
            urls.add(result.getMessage());
        }else{
            //保存失败
            System.out.println("fail:"+result.getMessage());
        }

        return "redirect:/showImg";
    }
    @RequestMapping("/showImg")
    public String getImgs(Model model){
        model.addAttribute("urls",urls);
        return "test/imglist";
    }
}

注意:访问时需要在springboot中将本地文件映射绑定在某指定的url上

WebMvcConfig中实现addResourceHandlers方法

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    // 从配置文件中取值,指定的数据位置信息,你也可以自由选择
    @Value("${file.img.path}")
    private String imgRealPath;
    @Value("${file.img.path.handler}")
    private String imgWebPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // imgWebPath 为web访问时对应的url地址
        // "file:" +imgRealPath 为存储在服务器(主机)中的地址
        registry.addResourceHandler(imgWebPath).addResourceLocations("file:"+imgRealPath);

 

}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值