java 单文件下载

一、前端代码

  //判断选中状态
        var ids ="";
        var num = 0;

        $(".checkbox").each(function () {
            if($(this).is(':checked')){
                ids +=$(this).val() + ",";
                num++;
            }
        });
        if(num <=0 ){
            toastr.error('请选择需要下载的文件!');
            return;
        }
        if(num > 1){
            toastr.error('页面下载只支持单个文件下载!');
            return;
        }
        ids = ids.slice(0,ids.length-1);
        // 拼接前端的form表单
        var tempForm = $('<form style="display:none;" id="tempFor" method="post" target="_blank" action="'+backbasePath+'/apia/v1/file/downloadFileById">' +
            '<input type="hidden" id="id" name="id" value="'+ids+'"/>' +
            '<input type="hidden" id="token" name="token" value="'+$("#token").val()+'"/></form>');
        // 将拼接的form表单加在body里面
        $('body').append(tempForm);
        //表单提交,调用后端的控制器
        tempForm.submit();
        //表单删除
        tempForm.remove();

二、控制器代码

   /**
     * 单文件下载
     */
    @RequestMapping(path = "/downloadFileById")
    public void downloadFileById(HttpServletRequest req, HttpServletResponse res) throws Exception {
        // 下载文件的集合
        Map<String, Object> downloadFile=knowledgeService.downloadFileById(req);
        if(downloadFile!=null && downloadFile.size()>0)
        {
       // 文件保存地址 String path
=downloadFile.get("file_path").toString();
       // 文件名称 String fileName
=downloadFile.get("file_real_name").toString();
       // 文件大小 String fileSize
=downloadFile.get("file_size").toString(); this.download(fileName,path,fileSize, res); } }

    // 具体文件下载的方法
    public HttpServletResponse download(String fileName,String path,String fileSize,HttpServletResponse response) {
        //读取文件上传路径
        String orgPath = "";
        orgPath = filePath+path;
            try {
            // 以流的形式下载文件
            InputStream fis = new BufferedInputStream(new FileInputStream(orgPath));
            // 定义字节数组用来当作缓冲区
            byte[] buffer = new byte[fis.available()];
            // 将文件以字节流形式读入缓冲区字节数组
            fis.read(buffer);
            // 关闭写入流
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName,"UTF-8"));
            response.addHeader("Content-Length", "" +fileSize);
            response.setCharacterEncoding("UTF-8");
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }

猜你喜欢

转载自www.cnblogs.com/flyShare/p/12498096.html