When downloading files, the back end will tell you the static directory path of the server. You can download the files directly from window.location.href. If the background server does not have static resources available for download and returns a file stream, use the following method; CreateObjectUrl () generates the URL, creates the a tag, href points to the URL, download points to the file name, triggers the click event, and then downloads.

URL.createObjectUrl()

The url.createObjecturl () static method creates a DOMString with a URL representing the object given in the argument. The lifecycle of this URL and the Document binding in the window that created it. This new URL object represents the specified File object or Blob object.

  • Syntax: objectURL = url.createObjecturl (object);

  • Parameter: object: File object, Blob object, or MediaSource object used to create the URL.

  • Return value: A DOMString contains an object URL that can be used to specify the contents of the source object.

Url.createobjecturl () this API needs to pass a parameter of type “File | Blob | MediaSource” to return a URL;

//@params fileStream is a file that needs to be downloaded from the back end. //@params fileName fileName; Const download = (fileStream: any, fileName? : string) => {// Generate url with fileStream; const url = window.URL.createObjectURL(new Blob([fileStream])); // Create an A tag; const link = document.createElement('a'); // Edit the href attribute of the a tag; link.href = url; // Edit the download attribute of the A tag (the default file name generated when the file is downloaded); link.setAttribute('download', fileName ? fileName : 'file'); // Add the a tag to the body; document.body.appendChild(link); // Click the event; link.click(); // Remove a tag; document.body.removeChild(link); };Copy the code

The following can be called:

const App = () => {
    const string = 'abc';
    const handleDownload = () => {
        download(string, '文本');
    };

    return <button onClick={handleDownload}>下载</button>
 }
Copy the code