最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Set filename to a Blob File - Stack Overflow

programmeradmin0浏览0评论

I would like to add a filename to my Blob file, but I don't really know how to do it, here is my code for the moment :

  onClick() {
    var myHeader = new Headers();

    myHeader.append('Content-Type', 'text/plain');

    fetch(this.props.url, {
      method: 'POST',
      headers: myHeader,
      body: JSON.stringify(this.state.api_arg)
    }).then(response => {
      const filename = getFileName(response.headers.get('Content-Disposition'))

      response.blob().then(myBlob => {
        const fileUrl = URL.createObjectURL(myBlob)

        console.log(fileUrl)
        window.open(fileUrl)
      })
    })
 }

my filename is stocked in a variable.

I would like to add a filename to my Blob file, but I don't really know how to do it, here is my code for the moment :

  onClick() {
    var myHeader = new Headers();

    myHeader.append('Content-Type', 'text/plain');

    fetch(this.props.url, {
      method: 'POST',
      headers: myHeader,
      body: JSON.stringify(this.state.api_arg)
    }).then(response => {
      const filename = getFileName(response.headers.get('Content-Disposition'))

      response.blob().then(myBlob => {
        const fileUrl = URL.createObjectURL(myBlob)

        console.log(fileUrl)
        window.open(fileUrl)
      })
    })
 }

my filename is stocked in a variable.

Share Improve this question edited Oct 15, 2018 at 9:39 Niels Steenbeek 4,8342 gold badges42 silver badges50 bronze badges asked Oct 15, 2018 at 9:30 asaasa 6411 gold badge8 silver badges21 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 10

The answer of Niels was incomplete, to handle filename in blob you have to do it that way:

const file = new File([myBlob], filename)

const url = URL.createObjectURL(myBlob);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
发布评论

评论列表(0)

  1. 暂无评论