前后台交互实现点击超链接通过指定的 url 去网络或者文件服务器下载文件

前台 VUE 界面:

<el-table-column prop="attachment" align="center" label="附件详情">
    <template slot-scope="scope">
        <!--<el-button @click="downloadFile(scope.row.fileName,scope.row.fileUrl)">{{scope.row.fileName}}</el-button>-->
        <a @click="downloadFile(scope.row.fileName,scope.row.fileUrl)">{{scope.row.fileName}}</a>
    </template>
</el-table-column>
//window.open打开一个新的浏览器窗口,通过 url 对后台的 rest 接口进行调用
downloadFile(fileName,fileUrl){ let param
= {"fileUrl": fileUrl, "fileName": fileName};   window.open(   downloadManage.downloadFile(param),   this.openType ); },
/* 下载文件,对参数 url 和 fileName 进行拼接处理,然后通过 window.open 对后台的 rest 接口进行调用 */
export const downloadManage = {
  downloadFile: (query) => requestGetUrl('/process/downloadFile.do_', query, 'post'),
};

后台java代码:(rest接口,供前台进行调用)

  /**
     * 下载文件   
     *
     * @return
     */
    @RequestMapping("/downloadFile.do_")
    @ResponseBody
    public void downloadFile(
            HttpServletResponse response,
            @RequestParam String fileUrl,
            @RequestParam String fileName
    ) {
        downLoadFromUrl(fileUrl,fileName,response);
    }

    /**
     * 从网络Url中下载文件
     * @param urlStr       指定的url
     * @param fileName     下载文件完成要叫的名字
     * @param response
     */
    public static void  downLoadFromUrl(String urlStr,String fileName,HttpServletResponse response){

        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    
         //增加头部,说明该文件为附件,只能进行下载,不直接读
            response.setContentType("application/x-msdownload; charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            //得到输入流
            InputStream inputStream = conn.getInputStream();

            BufferedInputStream bis = new BufferedInputStream(inputStream);
            OutputStream os = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(os);
            /* ContentLength必须设置,否则文件下载不全
             * 或者调用 BufferedOutputStream#write(byte[] b, int off, int len) 方法输出
             */
            response.setContentLength(bis.available());
            byte[] b = new byte[1024];
            while(bis.read(b) != -1) {
                bos.write(b);
            }
            bos.flush();


            LOGGER.info("info:"+fileName+" download success");
        } catch (IOException e) {
            LOGGER.error("uploadFile failed", e);
        }

    }

会出现如下通常我们网上点击某超链接下载文件的效果:(下载完成出现在浏览器页面左下角)

猜你喜欢

转载自www.cnblogs.com/liuqing576598117/p/9936400.html