download csv file from web api in angular js

前端 未结 10 1744
[愿得一人]
[愿得一人] 2020-11-28 03:23

my API controller is returning a csv file as seen below:

    [HttpPost]
    public HttpResponseMessage GenerateCSV(FieldParameters fieldParams)
    {
                


        
10条回答
  •  抹茶落季
    2020-11-28 04:16

    Workable solution:

    downloadCSV(data){   
     const newBlob = new Blob([decodeURIComponent(encodeURI(data))], { type: 'text/csv;charset=utf-8;' });
    
            // IE doesn't allow using a blob object directly as link href
            // instead it is necessary to use msSaveOrOpenBlob
            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
              window.navigator.msSaveOrOpenBlob(newBlob);
              return;
            }
    
            // For other browsers:
            // Create a link pointing to the ObjectURL containing the blob.
            const fileData = window.URL.createObjectURL(newBlob);
    
            const link = document.createElement('a');
            link.href = fileData;
            link.download = `Usecase-Unprocessed.csv`;
            // this is necessary as link.click() does not work on the latest firefox
            link.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
    
            setTimeout(function () {
              // For Firefox it is necessary to delay revoking the ObjectURL
              window.URL.revokeObjectURL(fileData);
              link.remove();
            }, 5000);
      }
    

提交回复
热议问题