栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring boot实现文件上传和文件下载(根据地址)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring boot实现文件上传和文件下载(根据地址)

1.导入相关pom以及配置文件路径
		
		
			cn.hutool
			hutool-all
			5.7.20
		
        
		
			org.apache.poi
			poi-ooxml
			4.1.2
		

 

 

用@Value来给需要的各种路径参数注入值

@Value("${file.path}")

private String filepath;

@Value("${server.ip}")

private String serverIp;

2.文件上传

解释说明:文件系统数据库设置MD5这个字段,MD5可以用来校验文件是否重复,重复就不上传,避免资源的浪费。同时在存储文件的同时还应该将文件各种类型参数写入数据库保存记录。

@PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String url="";
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件大小
        long size = file.getSize();
        //类型
        String type = FileUtil.extName(originalFilename);
        //创建父级目录
        File uploadParentFile=new File(filepath);
        if (!(uploadParentFile.exists())){
             uploadParentFile.mkdir();
        }
        //防止重名 定义文件标识码
        String uuid= IdUtil.simpleUUID();
        File uploadFile=new File(filepath+"/"+uuid+'.'+type);
        //获取文件MD5 校验是否重复文件
        String md5= SecureUtil.md5(file.getInputStream());
        //根据MD5去数据库校验是否存在
        SysFile serviceMd5 = fileService.findMd5(md5);
        //判断文件是否存在
        if (serviceMd5==null){
            //把获取file存入系统磁盘
           file.transferTo(uploadFile);
           url= "http://"+serverIp+":8081/file/"+uuid+'.'+type;
           SysFile saveFile=new SysFile();
           saveFile.setName(originalFilename);
           saveFile.setType(type);
           saveFile.setSize(size/1024);
           saveFile.setUrl(url);
           saveFile.setMd5(md5);
           fileService.saveFile(saveFile);
       }
        else {
            QueryWrapper queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("md5", md5);
            SysFile one = fileService.getOne(queryWrapper);
            url=one.getUrl();
        }

       return url;
    }
3.文件下载 根据UUID.文件类型 下载
    //根据uuid下载文件
    @GetMapping("/{fileUUID}")
    public void downFile(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
       //根据文件
       File uploadFile=new File(filepath+"/"+fileUUID);
       ServletOutputStream os=response.getOutputStream();
       response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(fileUUID,"UTF-8"));
       response.setContentType("application/octet-stream");
       //读取文件字节流
       os.write(FileUtil.readBytes(uploadFile));
       os.flush();
       os.close();
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/924269.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号