将IFormFile
更改为UploadPhotoRequest
-->多部分文件
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace UploadPhoto.Controllers
{
public class UploadPhotoRequest
{
public IFormFile File { get; set; }
public string Name { get; set; }
public string FileName { get; set; }
}
[ApiController]
[Route("api/v1/user")]
public class WeatherForecastController : ControllerBase
{
[HttpPost("uploadphoto")]
public string UploadPhoto([FromForm] UploadPhotoRequest file)
{
Console.WriteLine(file.Name);
return file.Name;
}
}
}
使用Postman集合进行验证
{"auth":null,"event":null,"info":{"_postman_id":null,"description":null,"name":"test.http","schema":"https://schema.getpostman.com/json/collection/v2.1.0/collection.json","version":null},"item":[{"description":null,"event":null,"id":null,"name":"1","protocolProfileBehavior":null,"request":{"auth":null,"body":{"disabled":null,"file":null,"formdata":[{"contentType":"application/json","description":null,"disabled":null,"key":"image","type":"file","value":"settings.json","src":null},{"contentType":null,"description":null,"disabled":null,"key":"name","type":"text","value":"ram","src":null}],"graphql":null,"mode":"formdata","options":null,"raw":null,"urlencoded":null},"certificate":null,"description":"1","header":null,"method":"POST","proxy":null,"url":"https://localhost:5001/api/v1/user/uploadphoto"},"response":null,"variable":null,"auth":null,"item":null}],"protocolProfileBehavior":null,"variable":null}
有两种上传文件的方式:
- 通过单个文件上传
- 通过多部分上传
如果需要上传多个文件/字段,则使用此选项。
在postman中上传单个文件
- 切换到body标签页
- 选择二进制
- 选择文件
![Single Binary](https://istack.dev59.com/pTEig.webp)
在postman中上传多部分文件
- 切换到body标签页
- 选择表单数据
- 添加键
如果是文件,请将鼠标悬停在键的右侧部分。您将看到将其更改为文件的选项。
![Multipart](https://istack.dev59.com/VFdTw.webp)
替代方案
Dothttp 是一款类似的工具,可以更好地控制这些内容。
对于单个文件
POST https://req.dothttp.dev
// select as a binary
fileinput('C:\Users\john\documents\photo.jpg') // path to file
关于分块上传
POST https://req.dothttp.dev
// selects as multipart
multipart(
'name'< 'john',
'photo'< 'C:\Users\john\documents\photo.jpg',
// and many more
)