zoukankan      html  css  js  c++  java
  • 【转载】关于MVC4.0 WebAPI上传图片重命名以及图文结合

    关于MVC4.0 WebAPI上传图片重命名以及图文结合

    MVC4.0 WebAPI上传后的图片默认以字符串bodypart结合Guid来命名,且没有文件后缀,为解决上传图片重命名以及图文结合发布的问题,在实体对象的处理上,可将图片属性定义为byte[]对象,至于图片的重命名,通过重写继承MultipartFormDataStreamProvider类来解决!

    参照API的官方文档,上传文件代码大致如下:

    复制代码
    public Task<HttpResponseMessage> PostFile()
            {
                HttpRequestMessage request = this.Request;         
    
                string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
                //var provider = new MultipartFormDataStreamProvider(root);//原写法
                var provider = new RenamingMultipartFormDataStreamProvider(root);//重命名写法
                //provider.BodyPartFileNames.sel(kv => kv.Value)
                var task = request.Content.ReadAsMultipartAsync(provider).
                    ContinueWith<HttpResponseMessage>(o =>
                    {
                        string file1 = provider.BodyPartFileNames.First().Value;
                        // this is the file name on the server where the file was saved                     
    
                        return new HttpResponseMessage()
                        {
                            Content = new StringContent("File uploaded." + file1)
                        };
                    }
                );
                return task;
            }
    复制代码

    再来看看继承MultipartFormDataStreamProvider的类:

    复制代码
    public class RenamingMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
        {
            public string Root { get; set; }
            //public Func<FileUpload.PostedFile, string> OnGetLocalFileName { get; set; }
    
            public RenamingMultipartFormDataStreamProvider(string root)
                : base(root)
            {
                Root = root;
            }
    
            public override string GetLocalFileName(HttpContentHeaders headers)
            {
                string filePath = headers.ContentDisposition.FileName;
    
                // Multipart requests with the file name seem to always include quotes.
                if (filePath.StartsWith(@"""") && filePath.EndsWith(@""""))
                    filePath = filePath.Substring(1, filePath.Length - 2);
    
                var filename = Path.GetFileName(filePath);
                var extension = Path.GetExtension(filePath);
                var contentType = headers.ContentType.MediaType;
    
                return filename;         
            }        
    
        } 待续...
    复制代码
  • 相关阅读:
    POJ2993——Emag eht htiw Em Pleh(字符串处理+排序)
    POJ2109——Power of Cryptography
    POJ2993——Help Me with the Game(字符串处理+排序)
    POJ1573——Robot Motion
    POJ2632——Crashing Robots
    POJ1068——Parencodings
    POJ3295——Tautology
    POJ2506——Tiling
    POJ2524——Ubiquitous Religions
    性能问题“三板斧”
  • 原文地址:https://www.cnblogs.com/fx2008/p/2817979.html
Copyright © 2011-2022 走看看