MultipartFormDataMemoryStreamProvider修正以支持非IIS宿主的情况

最近做上传,发现以前写的《WebAPI通过multipart/form-data方式接收文件时由开发自行决定如何保存文件》在owin下会取不到文件,所以这里重新修正了下,具体代码如下
    using System.IO;
    using System.Net.Http;
    using System.Net.Http.Headers;
    public class MultipartFormDataMemoryStreamProvider : MultipartFormDataStreamProvider
    {
        public MultipartFormDataMemoryStreamProvider()
            : base("/")
        {
        }

        public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
        {
            if (parent == null)
            {
                throw new ArgumentNullException("parent");
            }
            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }
            MemoryStream stream = new MemoryStream();
            if (IsFileContent(parent, headers))
            {
                MultipartFileData item = new MultipartFileDataStream(headers, string.Empty, stream);
                this.FileData.Add(item);
            }
            return stream;
        }
        private bool IsFileContent(HttpContent parent, HttpContentHeaders headers)
        {
            ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition;
            if (contentDisposition == null)
            {
                throw new InvalidOperationException("Content-Disposition error");
            }
            return !string.IsNullOrEmpty(contentDisposition.FileName);
        }
    }
    public class MultipartFileDataStream : MultipartFileData, IDisposable
    {
        /// <summary>
        /// file content stream
        /// </summary>
        public Stream Stream { get; private set; }
        public MultipartFileDataStream(HttpContentHeaders headers, string localFileName, Stream stream)
            : base(headers, localFileName)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            this.Stream = stream;
        }
        public void Dispose()
        {
            this.Stream.Dispose();
        }
    }
使用方式基本没变化,只是取Stream的地方有所调整
if (!Request.Content.IsMimeMultipartContent())
{
    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
Dictionary<string, string> dic = new Dictionary<string, string>();
#region 原来使用MultipartFormDataStreamProvider的方式
//string root = HttpContext.Current.Server.MapPath("~/App_Data");//指定要将文件存入的服务器物理位置
//var provider = new MultipartFormDataStreamProvider(root);
#endregion
string root = AppDomain.CurrentDomain.BaseDirectory;
var provider = new MultipartFormDataMemoryStreamProvider();
try
{
    // Read the form data.
    await Request.Content.ReadAsMultipartAsync(provider);

    // This illustrates how to get the file names.
    foreach (MultipartFileData file in provider.FileData)
    {//接收文件
        Trace.WriteLine(file.Headers.ContentDisposition.FileName);//获取上传文件实际的文件名
        Trace.WriteLine("Server file path: " + file.LocalFileName);//获取上传文件在服务上默认的文件名
        var stream = ((MultipartFileDataStream)file).Stream;
        using (StreamWriter sw = new StreamWriter(Path.Combine(root, file.Headers.ContentDisposition.FileName)))
        {
            stream.CopyTo(sw.BaseStream);
            sw.Flush();
        }
    }
    foreach (var key in provider.FormData.AllKeys)
    {//接收FormData
        dic.Add(key, provider.FormData[key]);
        Console.WriteLine($"Key:{key}  Value:{provider.FormData[key]}");
    }
}
catch(Exception ex)
{
    throw;
}


            
阅读更多
版权声明:本文为starfd原创文章,未经博主允许不得转载。 https://blog.csdn.net/starfd/article/details/53308651
文章标签: webapi Multipart
个人分类: C# WebAPI
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭