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

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日

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵