杏花怎酿酒 2022-08-11 07:38 采纳率: 55%
浏览 426
已结题

springboot vue 下载文件,浏览器未显示下载的文件 只有控制台 Preview 有文件

springboot vue 下载文件,浏览器未显示下载的文件
只有控制台 Preview 有文件

img

img


    @PostMapping("/down")
   public void down(HttpServletResponse response, @Param("id") int id) {
        Backup backup = backupService.getById(id);
          File file=new File(backup.getPath());
        response.setContentType ("application/octet-stream");
         
        String name = file.getName()+".txt";
        try {
            name = new String (name.getBytes (StandardCharsets.UTF_8), "ISO8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace ();
        }
        response.addHeader ("Content-Disposition", "attachment;filename=" + name);

        OutputStream opmt = null;

        try {
            opmt = response.getOutputStream ();
            opmt.write (FileUtils.readFileToByteArray (new File (backup.getPath())));
            opmt.close ();
        } catch (IOException e) {
            e.printStackTrace ();
        }
        
}

    async download({id}){ // id=
      const result = await getBackupDown({id}).catch(err=>{
        this.$message.error('网络请求错误')
      })
      if(result.status){
        this.$message.error('下载失败')
      }else {
        this.$message.success('下载成功')
      }

      await this.fetchData()
    },
<a-button value="small" @click="download(item)">下载</a-button>

  • 写回答

8条回答 默认 最新

  • 音药 2022-08-11 08:40
    关注
    
    this.$message.success('下载成功')
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=utf-8' })
        let link = document.createElement("a");
        let href = window.URL.createObjectURL(blob); //下载链接
        link.href = href;
        link.text = "下载";
        link.download = "xxx"; //下载后文件名
        document.body.appendChild(link);
        link.click(); //点击下载
        document.body.removeChild(link); //下载完成移除元素
        window.URL.revokeObjectURL(href);  //释放blob对象
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 8月14日
  • 已采纳回答 8月12日
  • 创建了问题 8月11日

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效