Upload component onDownload method configuration (with download method)

OnDownload method configuration of upload component in antdesign+React, attached download

When using the upload component in the background project of react+antd a few days ago, a download requirement was proposed. The upload component has two icons by default, preview and delete. If no preview is set, clicking the preview will directly open the file in a new window Address, onPreview in the official document:

onPreview Callback when a file link or preview icon is clicked function(file) -

And onDownload in the official document:

onDownload Callback when clicking to download a file, if not specified, it will jump to the tab corresponding to the file url by default function(file): void (Jump to new tab page)

At first, I thought that if I didn’t write a custom onPreview, I clicked the preview button to call onDownload and opened a new page, but when I customized the onDownload method, I clicked the preview button, but did not call handleDownload.

  <Upload
      listType="picture-card"
      fileList={fileList}
      onDownload={handleDownload}
   >
  const handleDownload = (file: any) => {
    
    
    console.log(file);
  };

Later, I checked the information and found that if I want to call the callback function of onDownload, I need to add a download button to the component, and then call it by clicking the download button.

showUploadList={
    
    {
    
     showDownloadIcon: true }}     //展示下载按钮

After configuration, you can call the download, the following is the complete code (including the download function)

   <Upload
     listType="picture-card"
     fileList={fileList}
     showUploadList={
     
     {
     
      showDownloadIcon: true }}
     onDownload={handleDownload}
   >
  //blob处理
  const getBlob = (url: string, cb: any) => {
    
    
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = function () {
    
    
      if (xhr.status === 200) {
    
    
        cb(xhr.response);
      }
    };
    xhr.send();
  };
  //文件路径处理
  const saveAs = (blob: any, filename: string) => {
    
    
    const link = document.createElement('a');
    const body = document.querySelector('body');
    link.href = window.URL.createObjectURL(blob);
    link.download = filename;
    // fix Firefox
    link.style.display = 'none';
    body!.appendChild(link);
    link.click();
    body!.removeChild(link);
    window.URL.revokeObjectURL(link.href);
  };
  //下载文件
  const handleDownload = (file: any) => {
    
    
    //这里的file做了处理是调用后端接口后返回了路径,前端拼接,所以有自定义的url和name。
    //url即下载路径,name即文件保存的名称。
    getBlob(file.url, function (blob: any) {
    
    
      saveAs(blob, file.name);
    });
  };

Ok, now onDownload returns to the function configuration and completes. If it helps you, please give me a thumbs up~

Guess you like

Origin blog.csdn.net/SJJ980724/article/details/126638005