The front-end processes the image/PDF that returns the stream type in the background

1. Project background

In the development process, in some cases, there is no way for the background to directly provide us with the path of pictures or PDFs for our front-end development and use, but the returned file stream. In this case, we have to do it ourselves.


2. Interface definition

We use the commonly used axios.jsplug-ins in the front end to request the interface provided by the background to return the binary stream. The code is as follows:

  const getBlobData = (data, options) =>{
    
    
  return axios.request({
    
    
    url: `/url/***`,
    responseType: 'blob',
    data: data,
    method: 'post'
  }).then(res=>{
    
    
     let blob = new Blob([res],options)
     let url =window.URL.createObjectURL(blob)
     return url
  })
}

3. Data processing

When we use axios to initiate a request, we need to set the response type responseType: 'blob'. After the request is initiated, we will get the stream data returned by the background, as shown in the figure:
insert image description here

BlobReceive stream data and create a class instance based on the returned data stream. The first parameter of the constructor is a stream array. The first parameter can pass an object to define the type of the file. When the stream file is a picture, the second parameter can not be passed. When the stream file is a pdf, it needs to be defined as, otherwise the browser cannot recognize the file type and cannot be previewed in the browser {type: 'application/pdf'}.

After getting the Blob instance, window.URL.createObjectURL()create an accessible url through the method. So far we can operate on the obtained url. It can be assigned to the attribute imgof the tag src, or window.open()previewed by .

ok call it a day!

Guess you like

Origin blog.csdn.net/eeefengzi/article/details/129288088
Recommended