Rob Fyffe
Rob Fyffe

Reputation: 729

How can I set the downloaded filename when using Filereader API?

I have a document as a base64string and then I generate the File from this and provide a download link. This all works correctly, however it gives the file a random number rather than the name I want.

Firstly I create a new file like so:

export const urlToFile = (url, filename, type) =>
  fetch(url)
    .then(res => res.arrayBuffer())
    .then(
      buffer =>
        new File([buffer], filename, {
          type
        })
    );

export const getExportFileUrl = resp =>
  urlToFile(
    `data:${docType};base64,${resp}`,
    `Document_Filename`,
    `${docType}`
  ).then(file => file);

I then combine Filereader and URL Api's to create the download link like so:


// This is returned from the File API.
const exportedFile = {
    name: "Document_Filename"
    lastModified: 1587577801489
    lastModifiedDate: '....'
    webkitRelativePath: ""
    size: 8243
    type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
}

handleDownloadClick = () => {
    const fileReader = new FileReader();

    fileReader.onload = () => {
        const downloadUrl = URL.createObjectURL(exportedFile);
        window.location = downloadUrl;
    };

    fileReader.readAsText(exportedFile);
};

The filename downloaded is something like:

f8477d6a-bea9-4a83-843f-26e381249b71.docx

How can I set my own filename, is this possible with the above implementation?

Upvotes: 0

Views: 605

Answers (1)

Rob Fyffe
Rob Fyffe

Reputation: 729

The solution was to utilize an anchor element rather than a button and then set the download attribute with the name I wanted for the file like so:

<a download="Name_2020_04_23_12_39" href="blob:http://domain">Download</a>

Upvotes: 1

Related Questions