如何从浏览器下载CSV文件

mo49yndu  于 2023-10-13  发布在  其他
关注(0)|答案(2)|浏览(293)

我想从浏览器上点击按钮下载文件。当我点击按钮时,什么也没有发生。我暂时存储在本地文件夹中的文件只是为了检查文件,我可以看到文件被存储。

API

[HttpGet]
    [Route("[controller]/downlaodCSV/{pID}/{customerID}")]
    public System.Net.Http.HttpResponseMessage downlaodCSV(int pID, int customerID)
    {
        //getting the file
        var rateFilename = _Client.RateRepository.downlaodCSV(pID, customerID);
        
            var stream = new System.IO.MemoryStream();
            processing the stream.

            var result = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK)
            {
                Content = new System.Net.Http.ByteArrayContent(stream.ToArray())
            };
            result.Content.Headers.ContentDisposition =
                new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                {
                    FileName = rateFilename
                };
            result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");

            return result;
    }

费率存储库:这是我的商业逻辑

public string downlaodCSV(int pID, int customerID)
    {
        Random _random = new Random();
        int number = _random.Next(1, 9999);

        string fileName = "";
        try
        {   
            #region Dummy Data            
            //Dummy Data for now -- this will be changed by correct data from the API
            DataTable rates = new DataTable();
            rates.Clear();
            rates.Columns.Add("Name");
            rates.Columns.Add("Surname");

            DataRow dr = rates.NewRow();
            dr["Name"] = "Test1";
            dr["Surname"] = "Test2";
            rates.Rows.Add(dr);

            #endregion

            if (rates.Rows.Count > 0)
            {
                StringBuilder stringBuilder = new StringBuilder();
                string[] columnNames = rates.Columns.Cast<DataColumn>(). Select(column => column.ColumnName).ToArray();
                stringBuilder.AppendLine(string.Join(",", columnNames));

                foreach (DataRow row in rates.Rows)
                {
                    string[] fields = row.ItemArray.Select(field => field.ToString()).ToArray();
                    stringBuilder.AppendLine(string.Join(",", fields));
                }

                fileName = CsvFilename(number);

                //Save to file to check the file. this will be deleted.
                string html = String.Empty;
                var newName = fileName;
                var path = @"C:\test\ " + newName + "";
                File.WriteAllText(fileName, stringBuilder.ToString());
                File.SetAttributes(fileName, FileAttributes.Normal);

                File.WriteAllText(path, html);
            }
            else
            {
                throw new Exception("Rates data to download not found!");
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
       return fileName;
    }

Component.ts

downloadFile()
{
    try
    {
        var _pID = this.reseller.pID;
        var _customerID = this.reseller.customerID;
        
            //Now calling download service
            this.rateSheetService.downlaodCSV(_pID, _customerID).then((obj) => {
                console.log("Api call made!!");
            ///1
            let blob: Blob = obj as Blob;
            console.log("blob", blob);

            var binaryData = [];
            binaryData.push(blob);
            console.log("binaryData", binaryData);
            var url = window.URL.createObjectURL(new Blob(binaryData, {type: "text/csv"}))
            console.log("Url", url);

            });
    }
    catch(e)
    {
        console.log("Checking the errors ", e)
    }
}

Service.ts

public downlaodCSV(pID, customerID){
    return this.apiService.get<any>(`RateSheetReport/downlaodCSV/${pID}/${customerID}`);
}

HTML

<button 
        class="context-download-button"
        (click)="downloadFile()"
        tooltipPosition="top">
        <span class="icon icon-download mr-5"></span>Download
    </button>

控制台日志和我从浏览器获得的响应

Blob console log

dm7nw8vv

dm7nw8vv1#

尝试将响应类型设置为blob

return this.apiService.get<any>(`RateSheetReport/downlaodCSV/${pID}/${customerID}`, { responseType: 'blob' });

然后像这样下载:

const link = document.createElement('a');
  if (link.download !== undefined) {
    
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', 'csv.csv');
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

另外,尝试在服务器上将内容类型头更改为text/csv

gmol1639

gmol16392#

尝试在a标记上设置属性hrefdownload

相关问题