ASP Net Core实现包含文本和文件的表单上传

Net Core实现很简单,整理并分享。
请求利用Postman来验证:


image.png

包含3个文本,2个文件,请求的报文结构如下:

POST /api/values/upload HTTP/1.1
Host: localhost:53119
Cache-Control: no-cache
Postman-Token: 6512f49a-225e-9388-74e7-8d350b8e6ad9
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="key1"

value1
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="key2"

value2
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file1"; filename="下载.png"
Content-Type: image/png


------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="key3"

value3
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file2"; filename="rsautils.c"
Content-Type: text/plain


------WebKitFormBoundary7MA4YWxkTrZu0gW--

创建一个web api项目,Controller里添加一个类ModelTest和一个函数接受表单提交:

public class ModelTest
{
    public string key1 { set; get; }
    public string key2 { set; get; }
    public string key3 { set; get; }
    public IFormFile file1 { set; get; }
    public IFormFile file2 { set; get; }
 }
[HttpPost("upload")]
public async Task<string> UploadFiles(ModelTest test)
{
    string key1 = test.key1;
    string key2 = test.key2;
    string key3 = test.key3;
    IFormFile file1 = test.file1;
    IFormFile file2 = test.file1;
    var path = Path.Combine(@"D:\temp", file1.FileName);
    using (var stream = System.IO.File.Create(path))
    {
        //保存到本地
        await file1.CopyToAsync(stream);
    }
    return "OK";
}

源码上传于git,以示参考

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容