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

本文介绍了一种改进的文件上传方法,在OWIN环境下通过自定义MultipartFormDataMemoryStreamProvider来处理multipart/form-data类型的文件上传请求,实现了文件内容的内存流读取及保存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近做上传,发现以前写的《 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;
}


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值