This is the sixth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Application scenarios

This function handles some general post download functions by reading the file stream, processing the BLOB stream to identify the address for the browser, and returning the callback processing method, or obtaining the ADDRESS of the BLOB stream for other operations.

For example: PDF preview

The solution

Plan a

Unified processing obtain bloB stream address and post form download function combined as a method processing

  1. The processing method of filesBlobDeal is introduced
import { filesBlobDeal } from '@/utils/common';
Copy the code
  1. Call the filesBlobDeal handling method
let fileObj = {
 reqType: ' '.// Interface request type: mandatory, pass "POST" or "GET"
 fileName: ' '.// File name: must be uploaded when downloading the file. Otherwise, do not upload the file. If ".pdf", ".png", ".zip" and other type suffixes need to be added.
 dealType: ' '.// File processing type: required, incoming downLoad file: 'downLoad' or preview processing blob stream for browser recognized address: 'blobUrl'
 paramObj: {}, // Input object value: this parameter is not required and is processed according to the business scenario
};
const hide = message.loading('Downloading.. '.0); // Processing loading tips: downloading.. In the load.. And so on, according to the need to modify the scene
filesBlobDeal(url, fileObj, (code, msg, blobUrl) = > {
  if (code == 200) {
    if(msg){message.success(msg); };// The following handles the business logic after the callback is successful

 } else if (code == 30001) {
    message.info(msg);
 } else {
    message.error('Request exception! ');
 }
  hide(); // Close the loading prompt
});
Copy the code

Note: if use method for blob stream address, need to use after the completion of the according to the callback method to derive blobUrl using Windows. URL. RevokeObjectURL (URL); To clear the objects created by releasing createObjectURL.

  1. FilesBlobDeal Logical processing method
Callback (code, MSG, blobUrl) : callback(code, MSG, blobUrl) : callback(code, MSG, blobUrl) : callback(code, MSG, blobUrl) : callback(code, MSG, blobUrl) : callback * code interface response status code: 200 normal others (400,500, etc.) 30001: no permission exception (interface definition) : call failed, MSG: exception message, blobUrl: address of blob identified by browser * let fileObj = {reqType: // Interface request type: mandatory, pass "POST" or "GET" fileName: ", // File name: not required. It is required when downloading the file. In other cases, it is not required. ", // File processing type: required item, downLoad file: 'downLoad' or preview processing blob flow for the browser to identify the address: 'blobUrl' paramObj: {}, // Input object value: not required item, according to the service scenario processing}; * /
export function filesBlobDeal(url, fileObj, callback) {
  getFilesBlob(url, fileObj, function (code, blob) {
    let reader = new FileReader();
    // Called when the read operation is complete
    reader.onload = function (event) {
      let content = reader.result;                         // After the read is complete, get the content of the file stream
      const url = window.URL.createObjectURL(blob);
      if(fileObj && fileObj.dealType && fileObj.dealType == 'downLoad') {// Download the file
        let fileType = fileObj.fileName.slice(fileObj.fileName.lastIndexOf('. ') + 1).toLowerCase();
        if(fileType == 'pdf') {if (content.indexOf('PDF') > -1) {               // If the file is PDF type keyword
            const a = document.createElement("a");
            a.href = url;
            a.download = fileObj.fileName;                 // File name
            a.click();
            window.URL.revokeObjectURL(url);               // The browser will automatically release the objects created by createObjectURL
            callback && callback(code, "Download complete!");
          }else {
            callback && callback(30001."You are not authorized to download this file"); }}else{
          const a = document.createElement("a");
          a.href = url;
          a.download = fileObj.fileName;                   // File name
          a.click();
          window.URL.revokeObjectURL(url);                 // The browser will automatically release the objects created by createObjectURL
          callback && callback(code, "Download complete!"); }}else{                                               // Previewing processes the bloB stream as an address recognized by the browser
        callback && callback(code,undefined,url); }}; reader.readAsText(blob);// Read the text file
  });
}
// Get the Blob value of the file
function getFilesBlob(url, fileObj, callback) {
  let xhr;
  if (typeofXMLHttpRequest ! ='undefined') {
    xhr = new XMLHttpRequest();
  } else {
    xhr = new ActiveXObject('Microsoft.XMLHTTP');
  };
  xhr.open(fileObj.reqType, url, true);
  xhr.responseType = "blob";
  let paramsObjStr = ' ';
  if(fileObj.paramObj){                                    // Request parameters
    xhr.setRequestHeader("Content-Type"."application/json");
    paramsObjStr = JSON.stringify(fileObj.paramObj);
  }
  xhr.onload = function () {
    if (this.status == 200) {
      if (callback) callback(200.this.response);
    }
    else {
      if (callback) callback(this.status); }};if(fileObj.paramObj){
    xhr.send(paramsObjStr);
  }else{
    xhr.send();
  };
}
/* * The browser will automatically release the objects created by createObjectURL */
export function releaseBlobUrl(url) {
  window.URL.revokeObjectURL(url);
}
Copy the code

Scheme 2

Description: Obtain file BLOB stream address and post form download function split into a single method processing (recommended)

  1. The downloadFiles processing method is introduced
import {downloadFiles } from '@/utils/common';
Copy the code
  1. Call the downloadFiles handling method
  • Simple Windows automatic download: just pass in the spliced parameters of the download address on the line
downloadFiles(url); // For example: '/**/**/download? id=120'
Copy the code
  • Download bloB files in POST mode
let fileObj = {
  reqType: ' '.// Interface request type: mandatory, pass "POST" or "GET"
  fileName: ' '.// File name: mandatory. The suffix ".pdf", ".png", and ".zip" must be added
  paramObj: {}, // Input object value: this parameter is not required and is processed according to the business scenario
 };
 const hide = message.loading('Downloading.. '.0); // Processing loading tips: downloading..
 downloadFiles(url, fileObj, (code, msg) = > {
   if (code == 200) {
     if(msg){message.success(msg); }; }else if (code == 30001) {
     message.info(msg);
  } else {
     message.error('Download exception! ');
  }
   hide(); // Close the loading prompt
 });
Copy the code
  • DownloadFiles Processing method:
Callback (code, MSG) : callback(code, MSG) : callback(code, MSG) : callback(code, MSG) : callback(code, MSG) : Callback method * code interface response status code: 200 normal others (400,500, etc.) 30001: no permission exception (interface definition) : call failed, MSG: exception message * let fileObj = {reqType: ", // Interface request type: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj: paramObj {}, // Input object value: non-mandatory items, according to the business scenario}; * /
    export function downloadFiles(url, fileObj, callback) {
      if(fileObj){
        getFilesBlob(url, fileObj, function (code, blob) {
          let reader = new FileReader();
          // Called when the read operation is complete
          reader.onload = function (event) {
            let content = reader.result;                        // After the read is complete, get the content of the file stream
            const url = window.URL.createObjectURL(blob);
            let fileType = fileObj.fileName.slice(fileObj.fileName.lastIndexOf('. ') + 1).toLowerCase();
            if(fileType == 'pdf') {if (content.indexOf('PDF') > -1) {               // If the file is PDF type keyword
                const a = document.createElement("a");
                a.href = url;
                a.download = fileObj.fileName;                 // File name
                a.click();
                window.URL.revokeObjectURL(url);               // The browser will automatically release the objects created by createObjectURL
                callback && callback(code, "Download complete!");
              }else {
                callback && callback(30001."You are not authorized to download this file"); }}else{
              const a = document.createElement("a");
              a.href = url;
              a.download = fileObj.fileName;                   // File name
              a.click();
              window.URL.revokeObjectURL(url);                 // The browser will automatically release the objects created by createObjectURL
              callback && callback(code, "Download complete!"); }}; reader.readAsText(blob);// Read the text file
        });
      }else{
        window.location.href = url;                            // If only the URL is passed (no fileObj, callback parameter), the default is to process the window automatic download}}Copy the code
  1. Gets the file BLOB stream address
  • Introduce the getFilesBlobUrl processing method
import {getFilesBlobUrl } from '@/utils/common';
Copy the code
  • Call the getFilesBlobUrl handling method
let fileObj = {
  url: ' '.// The interface requests the address
  paramObj: {},        // Input object value: this parameter is not required and is processed according to the business scenario
};
const hide = message.loading('File reading.. '.0);        // Processing loading tips: downloading.. In the load.. And so on, according to the need to modify the scene
getFilesBlobUrl(fileObj, (code, blobUrl) = > {
  if (code == 200) {
    // The following handles the business logic after the callback is successful
 
  } else {
    message.error('Request exception! ');
  }
  hide();             // Close the loading prompt
});
Copy the code
  • GetFilesBlobUrl Processing method

FileObj: callback(code, blobUrl) : callback(code, blobUrl) : callback(code, blobUrl) : callback(code, blobUrl) : * let fileObj = {url: ", // Interface request address paramObj: {}, // Input object value: non-mandatory item, processing based on the service scenario}; * /
    export function getFilesBlobUrl(fileObj, callback) {
      fileObj.reqType = 'POST';                                // By default, only post format is processed
      getFilesBlob(fileObj.url, fileObj, function (code, blob) {
        let reader = new FileReader();
        // Called when the read operation is complete
        reader.onload = function (event) {
          const url = window.URL.createObjectURL(blob);
          callback && callback(code,url);                      // Previewing processes the bloB stream as an address recognized by the browser
        };
        reader.readAsText(blob);                               // Read the text file
      });
    }
Copy the code
  • To use the bloB stream that has been created, the resource needs to be destroyed and released in time: call the releaseBlobUrl handling method
import {releaseBlobUrl } from '@/utils/common';
releaseBlobUrl(url);        // Url: address to be released, that is, just obtained blobUrl
Copy the code

Praise support, hand stay fragrance, and have glory yan, move your small hand to make a fortune yo, thank you for leaving your footprints.

Past excellent recommendation

Front ten thousand literal classics – basic

Front swastika area – advanced chapter

Let’s talk about two of the most common administrative tools used in front-end development

Talk about regular expressions

Hand touch hand take your liver Nodejs (1)