Background came stream file, how to achieve front-end file download

These two days, in the process log download function, the backstage pass front-end interfaces in the form of a binary stream file, as a new own Meng, also find a lot of information to process. Although there are many online methods, but really on their application and the code is valid, it is really not easy. After work, quickly summarize the accumulated experience for themselves.

Background came stream file, call interface successfully, found response is the case, the original is a background file transfer stream data, the need for front-end stream file processing, file compression download.

Call back interface state 200, but do not always go then jump to catch the code and the code, then certainly there is an error in the code, so do not go then code. Own time on someone else postForm package axios code is encapsulated get the axisos, the result is unnecessary. In fact, the direct use of the following way on the line.

In the store.js

//肯定是有params且params={'fileName:fileName,'filePath:filePath'}
该方法名为wwww
axios
.get(
  '/eng/downlog?fileName-&(params.fileName)&filePath=&(params.filePath)
) .then(response => { 
  console.log(response); 
}) .catch(function (error) { 
  console.log(error); 
});

In () method xx.vue download in downLOg

downLOg(fileName,filePath){

let params = {
  'fileName:fileName,
  'filePath:filePath'
}
this.$stroe.dispatch('wwww',params)
.then(response => {
   const blob = new Blob([response]);
   const downloadElement = document.createElement("a");
   const href = window.URL.createObjectURL(blob);
   const name = params.fileName;
   downloadElement.href = href;
   downloadElement.download = name;
   document.body.appendChild(downloadElement);
   downloadElement.click();
   document.body.removeChild(downloadElement);
   window.URL.revokeObjectURL(href);
})
.catch(err => {

})
}

Logs can be downloaded .zip archive file.

But the downloaded archive, open, enhance the file has been damaged. The original is not responseType: 'blob'.

In store.js supplemented as follows:

.get(
  '/eng/downlog?fileName-&(params.fileName)&filePath=&(params.filePath),{responseType:'blob'}
) .then(response => { 
  console.log(response); 
}) .catch(function (error) { 
  console.log(error); 
});

Go to the download package, it found that can be downloaded, but also normal decompression.

Guess you like

Origin www.cnblogs.com/LYD312/p/12031531.html