webapi读取上传的文件流

2021-06-06 20:03

阅读:646

标签:headers   tca   ssi   RKE   ev3   img   atm   zrm   dir   

逻辑说明

这里未引用System.Web.Mvc。
主要使用MultipartMemoryStreamProvider对象从Request中获取文件流。

var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var items = provider.Contents.Where(c => c.Headers.ContentDisposition.FileName != null);

这里读取到的是所有带有文件名的http内容。

完整代码

扩展ApiController方法。

public static class ApiExtensions
{
    public async static TaskFormFileCollection> ReadFileCollectionAsync(this ApiController apiController)
    {
        var provider = new MultipartMemoryStreamProvider();
        await apiController.Request.Content.ReadAsMultipartAsync(provider);
        var items = provider.Contents.Where(c => c.Headers.ContentDisposition.FileName != null);
        FormFileCollection files = new FormFileCollection();
        foreach (var item in items)
        {
            var disposition = item.Headers.ContentDisposition;
            FormFile file = new FormFile(disposition.Name.Trim(‘"‘), disposition.FileName.Trim(‘"‘), item.Headers.ContentType.MediaType, await item.ReadAsStreamAsync(), item.Headers.ContentLength ?? 0);
            files.Add(file);
        }
        return files;
    }

    public static FormFileCollection ReadFileCollection(this ApiController apiController)
    {
        using (var t = ReadFileCollectionAsync(apiController))
        {
            t.Wait();
            return t.Result;
        }
    }
}

使用方法:
技术图片

public IHttpActionResult Upload()
{
    var dir = "/upload/file";
    var dirPath = HostingEnvironment.MapPath(dir);
    if (!Directory.Exists(dirPath))
    {
        Directory.CreateDirectory(dirPath);
    }
    var files = this.ReadFileCollection();
    var fileA = files["filea"];
    fileA.SaveAs(Path.Combine(dirPath, fileA.FileName));
    var fileD = files["filed"];
    fileD.SaveAs(Path.Combine(dirPath, fileD.FileName));
    return Ok();
}

FormFile类:

public class FormFile
{
    public FormFile(string name, string fileName, string contentType, Stream stream, long size)
    {
        this.Name = name;
        this.FileName = fileName;
        this.ContentType = contentType;
        this.Stream = stream;
        this.Size = size;
    }

    public string Name { get; private set; }
    public string FileName { get; private set; }
    public string ContentType { get; private set; }
    public long Size { get; private set; }
    public Stream Stream { get; private set; }

    public virtual void SaveAs(string filename)
    {
        using (var fileStream = new FileStream(filename, FileMode.Create))
        {
            byte[] buffer = new byte[4096];
            while (true)
            {
                int num = this.Stream.Read(buffer, 0, buffer.Length);
                if (num == 0)
                {
                    break;
                }
                fileStream.Write(buffer, 0, num);
            }
            fileStream.Flush();
        }
    }
}

FormFileCollection类:

public class FormFileCollection : IEnumerableFormFile>
{
    readonly ListFormFile> files = new ListFormFile>();
    public int Count => files.Count;

    public FormFile this[int index]
    {
        get { return files[index]; }
    }

    public FormFile this[string index]
    {
        get { return files.Where(f => f.Name == index).FirstOrDefault(); }
    }

    public void Add(FormFile item)
    {
        files.Add(item);
    }

    public void AddRange(IEnumerableFormFile> items)
    {
        files.AddRange(items);
    }

    public IEnumeratorFormFile> GetEnumerator()
    {
        return files.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

webapi读取上传的文件流

标签:headers   tca   ssi   RKE   ev3   img   atm   zrm   dir   

原文地址:https://www.cnblogs.com/junio/p/10765633.html


评论


亲,登录后才可以留言!