Springboot+MybatisPlus实现从数据库保存的路径下载文件(2)

Springboot+MybatisPlus实现从数据库保存的路径下载文件(2),第1张

Springboot+MybatisPlus实现从数据库保存的路径下载文件(2)

还是用上次文件上传的数据库测试

 文件上传:

Springboot+MybatisPlus实现文件上传到服务器并保存路径到数据库(1)_HackAzrael的专栏-CSDN博客首先建立测试用的数据库CREATE TABLE `file` ( `id` bigint NOT NULL COMMENT '主键', `filename` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '文件名', `filepath` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULThttps://blog.csdn.net/HackAzrael/article/details/120984636

pom依赖


        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
        
            mysql
            mysql-connector-java
            runtime
        

        
        
            org.projectlombok
            lombok
            true
        

        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.4.3
        
        
            com.baomidou
            mybatis-plus-generator
            3.3.2
        
        
            org.springframework.boot
            spring-boot-starter-freemarker
        

        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        

        
        
            io.springfox
            springfox-swagger2
            3.0.0
        
        
            io.springfox
            springfox-swagger-ui
            2.9.2
        

        
        
            com.alibaba
            fastjson
            1.2.73
        
        
            javax
            javaee-api
            7.0
        
    

配置文件(application.yml)

mybatis-plus:
    mapper-locations: classpath:mybatis/mapper
@Controller
@RequestMapping("/file")
public class FileController {

    @Resource
    private FileService fileService;


    @ApiOperation("文件下载")
    @ApiResponses({
            @ApiResponse(code = 200,message = "下载成功"),
            @ApiResponse(code = 510,message = "下载失败"),
    })
    @ApiImplicitParam(name = "id",value = "文件主键id",dataType = "int",
            example = "902727344566087680",required = true)
    @GetMapping("/fileDownload")
    public @ResponseBody
    Map fileDownload(final HttpServletResponse response, long id)throws Exception{
        Map map = new HashMap<>();
        //通过Mybatis-plus自带的方法根据id查询文件详情
        File file = fileService.getById(id);
        //获取文件路径
        String filePath = file.getFilepath();
        //获取文件名
        String fileName = file.getFilename();
        FileDownloadUtils downloadUtils = new FileDownloadUtils();
        boolean res = downloadUtils.download(response, filePath, fileName);
        if (res) {
            map.put("code",200);
            map.put("success",true);
            map.put("message","下载成功!");
        }else {
            map.put("code",510);
            map.put("success",false);
            map.put("message","下载失败!");
        }
        return map;
    }

}

因为只使用了Mybatis-plus自带的方法查询,这里的业务层、业务层实现类和数据层就不做展示了

FileDownloadUtils

注意:这里的fileName是从数据库中查到的fileName,也就是带前后缀名的文件名

public class FileDownloadUtils {

    public boolean download(final HttpServletResponse response,
                            String filePath,
                            String fileName) throws Exception{
        //获得文件
        File file = new File(filePath);

        //清空缓冲区,状态码和响应头(header)
        response.reset();
        //设置ContentType,响应内容为二进制数据流,文件内容编码为UTF-8
        response.setContentType("application/octet-stream;charset=utf8");
        //设置默认的文件名并设置文件名的编码
        response.setHeader("Content-Disposition","attachment;fileName="+ fileName +";filename*=utf-8''"+ URLEncoder.encode(fileName,"utf-8"));

        //文件下载
        byte[] buffer = new byte[10240];
        FileInputStream fileInputStream = null;
        BufferedInputStream bufferedInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            bufferedInputStream = new BufferedInputStream(fileInputStream);
            //获取字节流
            OutputStream outputStream = response.getOutputStream();
            int i = bufferedInputStream.read(buffer);
            while (i != -1){
                outputStream.write(buffer, 0, i);
                i = bufferedInputStream.read(buffer);
            }
            return true;
        }catch (Exception e){
            return false;
        }finally {
            if (bufferedInputStream != null){
                try {
                    bufferedInputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            if (fileInputStream != null){
                try {
                    fileInputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
}

然后我们用Postman去测试接口是否可以正常使用

 这里其实是可以正常显示的,我们点击右边的Save Response->Save to a file保存为文件就可以了

这里的文件名是我们在工具类中设置过的默认文件名

测试可用,结束!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4874026.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-11
下一篇 2022-11-11

发表评论

登录后才能评论

评论列表(0条)

保存