美文网首页程序员
ASP Net Core实现包含文本和文件的表单上传

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

作者: voxer | 来源:发表于2018-03-07 13:42 被阅读85次

    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,以示参考

    相关文章

      网友评论

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

        本文链接:https://www.haomeiwen.com/subject/sisjfftx.html