MVC5 實現文件上傳

上傳帶有文件的參數時,需要用到MultipartMemoryStreamProvider。form參數可以通過改寫MultipartMemoryStreamProvider來獲取,話不多說,詳細代碼如下:



using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace ****.Common
{
    public class MultipartFormDataMemoryStreamProvider : MultipartMemoryStreamProvider
    {
        private readonly Collection<bool> _isFormData = new Collection<bool>();
        public Collection<MultipartFileData> FileData = new Collection<MultipartFileData>();
        public readonly NameValueCollection FormData = new NameValueCollection(StringComparer.OrdinalIgnoreCase);

        public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
        {
            if (parent == null)
            {
                throw new ArgumentNullException("parent");
            }
            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }

            var contentDisposition = headers.ContentDisposition;
            if (contentDisposition != null)
            {
                _isFormData.Add(String.IsNullOrEmpty(contentDisposition.FileName));
            }

            MemoryStream stream = new MemoryStream();
            if (IsFileContent(parent, headers))
            {
                MultipartFileData item = new MultipartFileDataStream(headers, string.Empty, stream);
                FileData.Add(item);
            }
            return stream;
        }

        public override async Task ExecutePostProcessingAsync()
        {
            for (var index = 0; index < Contents.Count; index++)
            {
                if (IsStream(index))
                    continue;
                var formContent = Contents[index];
                var contentDisposition = formContent.Headers.ContentDisposition;
                var formFieldName = UnquoteToken(contentDisposition.Name) ?? string.Empty;
                var formFieldValue = await formContent.ReadAsStringAsync();
                FormData.Add(formFieldName, formFieldValue);
            }
        }

        public bool IsStream(int idx)
        {
            return !_isFormData[idx];
        }

        private static string UnquoteToken(string token)
        {
            if (string.IsNullOrWhiteSpace(token))
                return token;
            if (token.StartsWith("\"", StringComparison.Ordinal) && token.EndsWith("\"", StringComparison.Ordinal) && token.Length > 1)
                return token.Substring(1, token.Length - 2);
            return token;
        }


        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");
                }
                Stream = stream;
            }
            public void Dispose()
            {
                Stream.Dispose();
            }
        }
    }
}

public async Task<HttpResponseMessage> Post()
        {
            string result = "fail";

            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string root = HttpContext.Current.Server.MapPath("~/\\../***.Web/App_Data/Ent");
            var provider = new MultipartFormDataMemoryStreamProvider();

            await Request.Content.ReadAsMultipartAsync(provider);

            try
            {
                var formDate = provider.FormData;

                var model = JsonConvert.DeserializeObject<EnterpriseInfoModel>(provider.FormData["enterprise"]);
                var guid = new Guid(provider.FormData["guid"]);
                var ent_name = provider.FormData["ent_name"];

                foreach (MultipartFileData file in provider.FileData)
                {
                    var stream = ((MultipartFormDataMemoryStreamProvider.MultipartFileDataStream)file).Stream;
                    var fileName = file.Headers.ContentDisposition.FileName.Replace("\"", "");

                    if (!Directory.Exists(root + "\\" + ent_name))
                    {
                        Directory.CreateDirectory(root + "\\" + ent_name);
                    }

                    using (StreamWriter sw = new StreamWriter(Path.Combine(root + "\\" + ent_name, fileName)))
                    {
                        stream.CopyTo(sw.BaseStream);
                        sw.Flush();
                    }

                    model.Logo = ent_name + "\\" + fileName;

                    result = await bll.ModifyEnterprise(model, guid);
                }

            }
            catch (Exception ex)
            {
                throw;
            }
            
            return new HttpResponseMessage { Content = new StringContent(result, System.Text.Encoding.UTF8, "application/json") };
        }

不懂得可以評論提問!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章