栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【无标题】

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【无标题】

Java+Vue 从后台下载文件
  • 文件下载
    • 前端
          • 方式一
          • 方式二
    • Java后端

文件下载 前端 方式一
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对象
   })
 }
方式二
 
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();
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/872211.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号