js处理接口返回的二进制文件并下载,在线查看,空白问题

 const blob = new Blob([r.data]); //创建blod对象 
          const filename = item.fileName;  //下载文件的名称
          const downloadElement = document.createElement("a");  //创建a元素  
          const href = window.URL.createObjectURL(blob); //下载的链接
          downloadElement.href = href;
          [downloadElement.download] = [
            decodeURI(decodeURI(filename)),
          ]; //a元素添加download属性   
          document.body.appendChild(downloadElement); //添加元素
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放blob对

在线浏览文件

const blob = new Blob([r.data], {
        type: "application/pdf;chartset=UTF-8",
});
const href = window.URL.createObjectURL(blob);
window.open(href);

如果空白内容,尝试设置设置 responseType: “arraybuffer”, ArrayBuffer对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在 Java 中,可以通过接口返回二进制文件的方式是将二进制数据转换为字节数组,然后在接口方法中返回这个字节数组。以下是一个示例代码: ``` import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Path("/binary") public class BinaryFileResource { @GET @Path("/download") @Produces(MediaType.APPLICATION_OCTET_STREAM) public Response downloadFile() { try { String filePath = "/path/to/file"; // 文件路径 FileInputStream fis = new FileInputStream(filePath); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { bos.write(buffer, 0, len); } byte[] fileContent = bos.toByteArray(); return Response.ok(fileContent, MediaType.APPLICATION_OCTET_STREAM) .header("Content-Disposition", "attachment; filename=\"file.bin\"") .build(); } catch (IOException e) { e.printStackTrace(); return Response.serverError().build(); } } } ``` 在上面的示例中,我们使用 FileInputStream 读取文件数据,并将二进制数据写入 ByteArrayOutputStream 中。最后,我们通过 toByteArray() 方法将 ByteArrayOutputStream 中的数据转换为字节数组。然后,在 downloadFile() 方法中,我们使用 Response.ok() 方法返回一个 Response 对象,其中包含字节数组和相应的 MediaType。此外,我们还设置了 Content-Disposition 头,用于指定浏览器下载文件时的文件名。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长影缚苍龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值