美文网首页
【Spring MVC】上传文件与文件下载

【Spring MVC】上传文件与文件下载

作者: 谢随安 | 来源:发表于2017-12-19 15:33 被阅读47次
文件上传
@RequestMapping("/upload.do")
    public XXX addAttach( MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            //抛出错误
            ...
        } else {
            long startTime = System.currentTimeMillis();
            //防止文件名重复上传失败
            String fileName = startTime + file.getOriginalFilename();
            //指定上传目录,不指定盘符会自动保存到你的项目所在盘符
            String filePath = "/data/app/XXX/upload/";
            File fileDir = new File(filePath);
            //目录不存在则生成目录
            if (!fileDir.isDirectory()) {
                fileDir.mkdirs();
            }
            File newFile = new File(fileDir, fileName);
            file.transferTo(newFile);
            //在数据库保存文件记录
            ...
            //返回对应的视图或者模型XXX
            ...
        }
    }
文件下载

第一次写文件下载遇到了个坑,最开始我在前端弄了个下载事件触发的function(),这个function()发送Ajax请求给后端,按照网上的样例实现的文件下载后端代码,然而数据一直都是成功返回了浏览器却没有弹出下载。纠结了很久,发现不能使用Ajax请求文件下载,因为Ajax不能传输文件格式。

文件下载的两种前端实现方式:

  1. a标签弹出指定链接。
  2. 触发click事件,在对应的函数中使用window.open("链接")跳转到新的页面。
a标签弹出链接

前端(项目用的Vue,改了下样例代码把Vue相关的删掉了):

<a href="'http://dev.download.com/download.do?id='id" target="_blank">下载文件</a>

后端:

@RequestMapping("/download.do")
    public void download(Long id, HttpServletResponse response) throws IOException {
        // 通过id查询数据库,返回包含下载地址的视图模型
        // 模型和Service都是自己定义的
        GameWelfareAttach gameWelfareAttach = gameWelfareInfoService.getAttachById(id);
        // 通过地址打开文件
        File file = new File(gameWelfareAttach.getUrl());
        OutputStream os = null;
        if (file.exists()){
            try {
            response.setContentType("application/octet-stream; charset=utf-8");
            //URLEncoder 防止中文乱码
            response.setHeader("Content-Disposition", "attachment;filename=" +URLEncoder.encode(gameWelfareAttach.getName(), "UTF-8"));
            response.addHeader("Content-Length", "" + file.length());
            os = response.getOutputStream();
            os.write(FileUtils.readFileToByteArray(file));
            os.flush();
            }
            finally {
                if (os != null){
                    os.close();
                }
            }
        }
    }
触发click事件,在function函数中使用window.open("链接")跳转到新的页面。

前端:

<a href="#" @click.prevent="downloadFile(id)">下载文件 </a>
// 其实是downloadFile: function (id) { },不过因为是Vue的语法就改了下示例代码方便理解
downloadFile(obj) {
    var url = "/download.do?id="+id;
    window.open(url);
 }

后端:

    @RequestMapping("/download.do")
    public void download(Long id, HttpServletResponse response) throws IOException {
        // 通过id查询数据库,返回包含下载地址的视图模型
        // 模型和Service都是自己定义的
        GameRebateAttach gameRebateAttach = gameRebateInfoService.getAttachById(id);
        response.setContentType("application/octet-stream; charset=utf-8");
        //URLEncoder 防止中文乱码
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(gameRebateAttach.getName(), "UTF-8"));
        InputStream in = new FileInputStream(gameRebateAttach.getUrl());
        byte[] b = new byte[1024];
        int len = 0;
        OutputStream os = response.getOutputStream();
        while ((len = (in.read(b))) > 0) {
            os.write(b,0,len);
        }
        in.close();
    }

相关文章