【问题标题】:ASP Core WebApi Test File Upload using Postman使用 Postman 上传 ASP Core WebApi 测试文件
【发布时间】:2018-04-04 08:46:15
【问题描述】:

我创建了一个接收任意文件的端点:

[HttpPost()]
public async Task<IActionResult> CreateFile(IFormFile file)

当我用 Postman 测试它时,file 始终为空。

这是我在 Postman 中所做的:

我做错了什么?

【问题讨论】:

  • 您是否尝试过使用表单数据?你应该有一种方法来“模拟”一个表单,通过指定字段,并添加文件
  • 我也有 Content-Type = application/x-www-form-urlencoded 的标题
  • 我让它与表单数据一起工作。我不需要添加内容类型标题。

标签: c# asp.net-web-api .net-core postman


【解决方案1】:

感谢@rmjoia 的评论,我得到了它的工作!这是我在 Postman 中必须做的事情:

【讨论】:

  • 我也想传输文件,但它帮助了我,谢谢。 @Zeus82 当我在请求中有其他 JSON 参数时,您能否解释或参考任何链接如何传输文件。
【解决方案2】:

上传文件的完整解决方案如下:

  • 此操作用于上传多个文件

    // Of course this action exist in microsoft docs and you can read it.
    HttpPost("UploadMultipleFiles")]
    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
    
        return Ok(new { count = files.Count, path = filePath});
    }
    

邮递员图片显示了如何将文件发送到此端点以上传多个文件:

  • 此操作用于上传单个文件

    [HttpPost("UploadSingleFile")]
    public async Task<IActionResult> Post(IFormFile file)
    {
    
        // Full path to file in temp location
        var filePath = Path.GetTempFileName();
    
        if (file.Length > 0)
            using (var stream = new FileStream(filePath, FileMode.Create))
                await file.CopyToAsync(stream);
    
        // Process uploaded files
    
        return Ok(new { count = 1, path = filePath});
    }
    

邮递员图片显示了如何将文件发送到此端点以上传单个文件:

【讨论】:

  • 这很好。我能够上传单个文件。但是,您对多个文件的示例,我继续在邮递员中收到错误(以下)。你见过这个吗? { "": [ "输入无效。" ] }
  • 为了发送多个文件,我不得不将我的方法签名更改为 ... public async Task UploadFiles(IFormFileCollection files) 使用 List 文件作为上传多个文件对我不起作用.
  • 对于发送多个文件, IFomFileCollection 和 List 都应该工作。如果您无法理解问题,您应该检查参数名称和模型验证。监控您的请求,因为有时请求与您期望的不同。
  • +1 给大卫。我也需要使用 IFormFileCollection。使用 List 对我也不起作用。我很好奇,我猜 List 应该也可以工作。
  • 只是一个注释要注意,使用这种 Postman 文件上传方法,请确保将表单数据中的“Key”名称与方法输入参数名称匹配,否则文件只会显示为空。例如:如果方法是 UploadFile(IFormFile myFile),请确保在 Postman 中将关键字段设置为“myFile”。
【解决方案3】:

你应该是这样的

 [HttpPost]       
   public async Task<IActionResult> UploadFile([FromForm]UploadFile updateTenantRequest)
        {
}

你的班级应该是这样的:-

public class UpdateTenantRequestdto
    {


        public IFormFile TenantLogo { get; set; }
    }

然后

【讨论】:

    【解决方案4】:
       [HttpPost("UploadSingleFile"), Route("[action]")]
        public async Task<IActionResult> UploadSingleFile([FromForm(Name = "file")] IFormFile file)
        {
    
    
            // Process uploaded files
    
            string folderName = "Uploads";
            string webRootPath = hostingEnvironment.WebRootPath;
            string newPath = Path.Combine(webRootPath, folderName);
            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }
    
            Repository.Models.File fileModel = new Repository.Models.File();
            fileModel.Name = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
            fileModel.Path = $"{folderName}/{file.FileName}";
            fileModel.Size = file.Length;
            fileModel.Type = file.ContentType;
    
            string fullPath = Path.Combine(newPath, fileModel.Name);
    
            fileModel.Extension = Path.GetExtension(fullPath);
            fileModel.CreatedDate = Utility.Common.GetDate;
            fileModel.CreatedBy = 1;
    
            //fileModel save to db
    
            using (var stream = new FileStream(fullPath, FileMode.Create))
            {
                //file.CopyTo(stream);
                await file.CopyToAsync(stream);
            }
    
            return Ok(new { count = 1, path = filePath });
        }
    

    【讨论】:

    • 欢迎来到 Stack Overflow!请不要只用源代码回答。尝试对您的解决方案如何工作提供一个很好的描述。请参阅:How do I write a good answer?。谢谢
    猜你喜欢
    • 2019-04-30
    • 2018-04-04
    • 2019-08-04
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    相关资源
    最近更新 更多