Java+Vue 从后台下载文件

文件下载

前端

方式一
downloadAttachment(fileSrc){
   let fileName = fileSrc.substring(fileSrc.lastIndexOf("/")+1,fileSrc.length);//获取文件名
   downLoadAttachment(fileSrc).then(response => {//自定义的vue请求,请求后台下载地址
     //以下均为后台请求返回成功后对返回结果的处理,处理完成会从浏览器显示下载
     let blob = new Blob([response]);//response是返回的数据对象
     let downloadElement = document.createElement('a');
     let href = window.URL.createObjectURL(blob); //创建下载的链接
     downloadElement.href = href;
     downloadElement.setAttribute('download', fileName)
     document.body.appendChild(downloadElement);
     downloadElement.click(); //点击下载
     document.body.removeChild(downloadElement); //下载完成移除元素
     window.URL.revokeObjectURL(href); //释放掉blob对象
   })
 }
方式二
 /*下载本地文件
 * 直接window.location.href请求后台下载地址即可
 */
export function downloadFile(fileName) {
  window.location.href = baseURL + "/common/download/resource?name=" + encodeURI(fileName);
}

Java后端

public static void download (String fileSrc, HttpServletRequest request,HttpServletResponse response)
            throws IOException {
      
        // 自己的资源路径,ftp,本地的等
        String filePath = ‘your own resource path’;
        //截取文件名
        String downloadName = StringUtils.substringAfterLast(filePath, "/");
        //返回最终的结果,使得浏览器可以响应下载
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        //3.设置content-disposition响应头控制浏览器以下载的形式打开文件
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
            File file = new File(filePath);
            if (!file.exists())
            {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0)
            {
                os.write(b, 0, length);
            }
            os.close();
            fis.close();
    }
Logo

前往低代码交流专区

更多推荐