gpt4 book ai didi

c# - 将 CSV 文件从 Angular7 传递到 MVC .Net Core

转载 作者:太空宇宙 更新时间:2023-11-03 14:45:02 24 4
gpt4 key购买 nike

我正在尝试将 CSV 文件传递​​到我的后端以利用库来解析 CSV 数据。

我有一个 Angular7 前端和一个 C# .Net Core MVC 后端,使用 typescript 中的 HttpClient 来将数据和对象传入和传出后端。

我已经尝试了很多解决方案,但收效甚微(最接近的是我可以在代码中访问 Controller ,但文件从未传入)。

我试图避免对 CSV 进行任何类型的序列化或转换,直到它到达 Controller ,所以我想找到一个可以将整个 CSV 发送到后端的解决方案。

如有任何帮助,我们将不胜感激。

service.ts

// Parse CSV
// The CSV always reaches this part of the code and I can inspect it.
parseCsv$(file: File): Observable<Dto> {
const request$ = this.http.post<Dto>(
location.origin + '/api/csvimport',
file,
{ headers: new HttpHeaders({ 'Content-Type': 'multipart/form-data' }) }
).pipe(
map((response: <Dto>) => response)
);

request$.subscribe();

return request$;
}

CsvImportController.cs

    [HttpPost]
[ProducesResponseType(typeof(Dto), 200)]

// The 'file' variable below is always null
public async Task<IActionResult> ParseCsv([FromBody]IFormFile file)
{
// do work here

最佳答案

您不应在文件上传中使用 FromBody 参数。

您应该使用 request.Form.Files collection获取上传的文件,或者

您可以在 Controller 操作中使用 IList,如下所示。

以下 API 获取文件列表,然后保存在服务器上的临时文件夹中。

[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);

// full path to file in temp location
var filePath = Path.GetTempFileName();

foreach (var formFile in files)
{
if (formFile.Length > 0)
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
}
}
}

// process uploaded files
// Don't rely on or trust the FileName property without validation.

return Ok(new { count = files.Count, size, filePath});
}

希望这对您有所帮助。

关于c# - 将 CSV 文件从 Angular7 传递到 MVC .Net Core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54773245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com