SpringBoot在线考试系统-上传图片到Docker中并且展示出来

本文介绍了如何在SpringBoot项目部署到Docker环境下,实现图片上传并展示的功能。通过设置配置文件、允许静态资源访问以及处理文件上传和读取,实现了在Docker容器中存储和显示图片的解决方案。

一 前言:

每个系统中,上传图片是必备可少的。而且也是常用的功能。但是SpringBoot项目,打包生成jar包,部署到docker中, 上传文件的路径,就需要大家特别注意。相信做个功能的小伙伴,遇到了这个坑。

二 文件上传的解决方案

​ 方案一: OSS对象存储 需要买存储服务器,对接SDK,费用成本大,小项目没有必要
​ 方案二: 直接上传到服务器上面,替换OSS对象存储的方案,费用成本小,适合小型的项目.
​ 我这里说的是第二种方案;

解决步骤:
第一步:
在application.properties或者 yml 中设置存储的地址
比如

       spring.thymeleaf.suffix=.html
	   spring.thymeleaf.encoding=UTF-8
       spring.thymeleaf.mode=HTML5 
       spring.thymeleaf.cache=false
       spring.mvc.static-path-pattern=/static/**/
       #centos服务器文件地址
       exam.upload.path=/usr/local/exam/upload
       #window版本文件地址
       exam.upload.path=D:\\xxx\\exam\\exam\\src\\main\\resources\\static\\upload

第二步: 添加静态资源放行

@Configuration
public class MyPicConfig implements WebMvcConfigurer{

//上传地址
@Value("${exam.upload.path}")
private String filePath;
   
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
   String os = System.getProperty("os.name");
   if (os.toLowerCase().startsWith("win")) { 
   	 //如果是Windows系统
       registry.addResourceHandler("/static/upload/**")
               .addResourceLocations("file:"+filePath); 
   } else {  
      //linux 和mac
       registry.addResourceHandler("/exam/upload/**")
               .addResourceLocations("file:"+filePath);
   }
}
}

第三步: 文件的上传 和 读取文件

	@RequestMapping(value="/file/uploadFile", method= RequestMethod.POST)
    @ResponseBody
   public AjaxResult upload(HttpServletRequest req, Integer id, @RequestParam("file") MultipartFile file){
        try {
            if(file.isEmpty()){
                return new AjaxResult("文件为空");
            }
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            String uuidString = UUID.randomUUID().toString();
            String newFileName= uuidString + suffixName;

            File path = new File(uploadPath);
            if (!path.exists()) path.mkdirs();

            File savefile = new File(path,newFileName);
            if (!savefile.getParentFile().exists()) savefile.getParentFile().mkdirs();
            file.transferTo(savefile);

            //更新用户表的头像
            User user = new User();
            user.setId(Long.parseLong(id+""));
            user.setHeadImg(newFileName);
            userService.updateUserHeadImg(user);

            return new AjaxResult();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "/showImage/{image_name}")
    public String showImage(@PathVariable("image_name") String image_name,HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        File fileParent = new File(File.separator);
        File file = null ;
        String os = System.getProperty("os.name");
        ServletOutputStream out = response.getOutputStream();
        try {
            if (os.toLowerCase().startsWith("win")) {
            	 //如果是Windows系统 
                file = new File(uploadPath +"\\"+ image_name);
            } else {  //linux 和mac
                file = new File(fileParent, uploadPath.substring(1) +"/"+ image_name);
            }
            IOUtils.copy(new FileInputStream(file),out);
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }

亲测可行哟!!!

完整源码 , 参考在线考试系统 https://gitee.com/soul_PreCoder/exam

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值