5

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.

Niels Steenbeek
  • 4,692
  • 2
  • 41
  • 50
asa
  • 531
  • 1
  • 5
  • 20

2 Answers2

5

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

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

asa
  • 531
  • 1
  • 5
  • 20
  • For the very small change, you could have better edited my answer instead of posting your own. – Niels Steenbeek Oct 15 '18 at 11:19
  • A variation of @asa's solution worked for me, specifically `new File(audioChunks, "Test.ogg",{ 'type' : 'audio/ogg; codecs=opus' })` used with an audio tag and MediaRecorder. See also: https://stackoverflow.com/a/60866282/889894 – SE Does Not Like Dissent Apr 27 '22 at 20:23
1
const url = URL.createObjectURL(myBlob);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();