发送到前端时如何解决后端csv下载未正确创建的问题

时间:2019-04-18 20:48:49

标签: c# reactjs asp.net-core asp.net-core-webapi

我正在尝试从数据库中以csv的形式从数据库下载一组数据。在浏览器上进行下载时,csv中仅包含[Object Object]。

目前,我在API控制器中拥有此功能:

        public HttpResponseMessage GetListCsv(string fileName)
        {
            var result = new HttpResponseMessage(HttpStatusCode.OK);
            var csv = _myService.DownloadCsv(fileName);                           

            var stream = new MemoryStream(new ASCIIEncoding().GetBytes(csv));
            result.Content = new StreamContent(stream);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = $"{fileName}.csv" };
            return result;
        }

这是在前端:

        axios.get('api/List/Csv?fileName=' + id, { responseType: 'arrayBuffer',
        headers: {
          'Accept': 'text/csv'
        } })
            .then(resp => {                
                const saveData = (function () {
                    const a = document.createElement("a");
                    document.body.appendChild(a);
                    a.style = "display: none";
                    return function (data, fileName) {
                        const blob = new Blob([data], { type: "text/csv" }),
                            url = window.URL.createObjectURL(blob);
                        a.href = url;
                        a.download = fileName;
                        a.click();
                        window.URL.revokeObjectURL(url);
                    };
                }());

                const fileName = id + ".csv";

                saveData(resp, fileName);

                this.fetchData();
            });
}

无论何时运行,都会在浏览器上使用正确的文件名进行下载,然后下载csv。但是,csv中唯一的东西就是[object object]。

在此方面的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

以下是您可以根据需要使用和更改的示例代码-

  1. 编写单独的函数以返回csv文件数据
        public async Task<CsvFileData> GetCsvFileDataAsync(DataModel model)
        {
            var csvFileData = new CsvFileData();

            using (var memoryStream = new MemoryStream())
            {
                using (var streamWriter = new StreamWriter(memoryStream))
                using (var csvWriter = new CsvWriter(streamWriter))
                {
                    csvWriter.WriteHeader<DataModel>();
                    csvWriter.NextRecord();
                    csvWriter.WriteRecord(model);
                }

                csvFileData.Content = memoryStream.ToArray();
            }

            csvFileData.Name = $"test.csv";

            return csvFileData;
        }
  1. 在控制器中
    var csvFileData = GetCsvFileDataAsync(model);
            if (csvFileData == null)
            {
               // log error and return proper status code
            }

            return File(csvFileData.Content, "text/csv", csvFileData.Name);