【问题标题】:.net5 API File Upload corrupting file.net5 API 文件上传损坏文件
【发布时间】:2021-12-16 12:34:08
【问题描述】:

我正在尝试为我们的 API 创建一个文档上传方法。文本文件上传正常,但 word 文档、pdf、图像最终都损坏了。如果我尝试上传一个 18kb 的图像文件,它会以正确的文件名和扩展名保存在正确的位置,但它突然变成了一个无法打开的 31kb 文件。

**Controller Method**
[HttpPost("{uid}/Document")]
public IActionResult SaveDocument(int uid, [FromForm] Document document)
{
    _entityService.SaveDocument(uid, UserUID, document);
    return StatusCode(StatusCodes.Status201Created);
}

**Service Method**
public async void SaveDocument(int uid, int userUID, Document document)
{
    try
    {
        string path = Path.Combine(Directory.GetCurrentDirectory(), "Temp", document.FileName);

        using (FileStream createStream = new(path, FileMode.Create))
            await document.FormFile.CopyToAsync(createStream);
    }
    catch(Exception ex)
    {
        EventLogger.LogException(ex);
        throw;
    }
}

**Model**
public class Document
{
    public IFormFile FormFile { get; set; }
    public byte[] bytes { get; set; }
    public string FileName { get; set; }
    public string ContentType { get; set; }
}

【问题讨论】:

  • 查看answer
  • @Pato 不确定你想让我在那里看到什么。可以肯定的是文件大小不是问题,因为我正在测试的文件远低于 100kb。
  • 对不起,我的错。你能分享你的发帖请求吗?你的方法好像没问题
  • 我通过 Postman 发帖。 POST,form-data,通过 Value 列添加文件。我的另一个队友设置了一个 React 页面来发布,我们得到了相同的结果。

标签: c# rest .net-5


【解决方案1】:

一些可能的原因:

  1. 您可以让防病毒/恶意软件/IDS 在后台执行某些操作。

  2. 当您尝试传输或转换时,您的文件会变得混乱。您可以检查 IFormFile 接口是否正确转换。

我已经测试了你的方法,一切都可以使用 IFormFile 作为参数。

using Microsoft.AspNetCore.Http;
// ...
[HttpPost("tester")]
[AllowAnonymous]
public async Task<ActionResult> Tester(IFormFile file)
{

  Document document = new() {
    FormFile = file,
    FileName = file.FileName,
    ContentType = file.ContentType,
  };

  string path = Path.Combine(Directory.GetCurrentDirectory(), "Temp", document.FileName);

  using (FileStream createStream = new(path, FileMode.Create))
    await document.FormFile.CopyToAsync(createStream);

  return Ok(new { success = true, message = "All set", file });
}

请求和结果:

【讨论】:

  • 所以我尝试了您对方法所做的更改,我看到的结果与以前相同。关于下一步我可以尝试什么,或者我可以测试您列出的可能问题的任何想法?
猜你喜欢
  • 1970-01-01
  • 2020-09-27
  • 2019-10-10
  • 1970-01-01
  • 1970-01-01
  • 2017-08-29
  • 1970-01-01
  • 2014-02-25
  • 1970-01-01
相关资源
最近更新 更多