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

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

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


public class FileUploadController : ApiController
{

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;//多张图片循环provider.BodyPartFileNames或provider.FileData
            //string file1 = provider.GetLocalFileName(provider.FileData[0].Headers);//返回重写的文件名(注意,由于packages包版本的不同,用BodyPartFileNames还是FileData需要留意)
// 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;         
        }        

    }

该方法通过直接指定form的action为请求的WebAPI上传地址来处理;如:

<form name="form1" method="post" enctype="multipart/form-data" action="http://localhost:8000/api/FileUpload/PostFile">。

另外我们还可以通过向WebAPI提交byte[]形式的文件来解决(以HttpClient方式向WebAPI地址提交上传对象),首先定义文件上传类,以最简单的为例:

相关上传实体类:

/// <summary>
/// 文件上传
/// </summary>
public class UploadFileEntity
{
    /// <summary>
    /// 文件名
    /// </summary>
    public string FileName { get; set; }
    /// <summary>
    /// 文件二进制数据
    /// </summary>
    public byte[] FileData { get; set; }    
}

/// <summary>
/// 文件上传结果信息
/// </summary>
public class ResultModel
{
    /// <summary>
    /// 返回结果 0: 失败,1: 成功。
    /// </summary>
    public int Result { get; set; }
    /// <summary>
    /// 操作信息,成功将返回空。
    /// </summary>
    public string Message { get; set; }   
}
View Code

上传的Action方法:

public ActionResult UploadImage()
        {
            byte[] bytes = null;
            using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
            {
                bytes = binaryReader.ReadBytes(Request.Files[0].ContentLength);
            }
            string fileExt = Path.GetExtension(Request.Files[0].FileName).ToLower();
            UploadFileEntity entity = new UploadFileEntity();
            entity.FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + fileExt;//自定义文件名称,这里以当前时间为例
            entity.FileData = bytes;

            ResultModel rm = HttpClientOperate.Post<ResultModel>("/UploadFile/SaveFile", APIUrl, entity);//封装的POST提交方法,APIUrl为提交地址,大家可还原为HttpClient的PostAsync方式提交
            return Content("{\"msg\":\"" + rm.Message + "\"}");

        }
View Code

 

WebAPI接收端,主要方法如下(Controller代码略):

public string SaveFile(UploadFileEntity entity)
{
    string retVal = string.Empty;
    if (entity.FileData != null && entity.FileData.Length > 0)
    {//由于此例生成的文件含子目录文件等多层,下面处理方法不一定适合大家,保存地址处理大家根据自己需求来
        entity.FileName = entity.FileName.ToLower().Replace("\\", "/");
        string savaImageName = HttpContext.Current.Server.MapPath(ConfigOperate.GetConfigValue("SaveBasePath")) + entity.FileName;//定义保存地址
        
        string path = savaImageName.Substring(0, savaImageName.LastIndexOf("/"));
        DirectoryInfo Drr = new DirectoryInfo(path);
        if (!Drr.Exists)
        {
            Drr.Create();
        }
        FileStream fs = new FileStream(savaImageName, FileMode.Create, FileAccess.Write);
        fs.Write(entity.FileData, 0, entity.FileData.Length);
        fs.Flush();
        fs.Close();
        #region 更新数据等其他逻辑
        #endregion
        retVal = ConfigOperate.GetConfigValue("ImageUrl") + entity.FileName;
    }
    return retVal;//返回文件地址
}
View Code

 

 Httpclient相关扩展方法如下:

public static T Post<T>(string requestUri, string webapiBaseUrl, HttpContent httpContent)
        {
            var httpClient = new HttpClient()
            {
                MaxResponseContentBufferSize = 1024 * 1024 * 2,
                BaseAddress = new Uri(webapiBaseUrl)
            };

            T t = Activator.CreateInstance<T>();

            HttpResponseMessage response = new HttpResponseMessage();

            try
            {
                httpClient.PostAsync(requestUri, httpContent).ContinueWith((task) =>
                {
                    if (task.Status != TaskStatus.Canceled)
                    {
                        response = task.Result;
                    }
                }).Wait(waitTime);

                if (response.Content != null && response.StatusCode == HttpStatusCode.OK)
                {
                    t = response.Content.ReadAsAsync<T>().Result;
                }
                return t;
            }
            catch { return t; }
            finally
            {
                httpClient.Dispose();
                response.Dispose();
            }
        }


public static T Post<T>(string requestUri, string webapiBaseUrl, string jsonString)
        {
            HttpContent httpContent = new StringContent(jsonString);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return Post<T>(requestUri, webapiBaseUrl, httpContent);
        }


public static T Post<T>(string requestUri, string webapiBaseUrl, object obj = null)
        {
            string jsonString = JsonOperate.Convert2Json<object>(obj);//可换成Newtonsoft.Json的JsonConvert.SerializeObject方法将对象转化为json字符串
            return Post<T>(requestUri, webapiBaseUrl, jsonString);
        }

  简单调用示例如下:

UploadFileEntity entity = new UploadFileEntity();
entity.FileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + fileExt;//自定义文件名称,这里以当前时间为例
entity.FileData = GetByte(Request.Files[0].InputStream);

var request = JsonConvert.SerializeObject(entity);
HttpContent httpContent = new StringContent(request);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

var httpClient = new HttpClient();
httpClient.PostAsync("http://localhost:7901/api/FileUpload/SaveFile", httpContent);


public static byte[] GetByte(Stream stream)
        {
            byte[] fileData = new byte[stream.Length];
            stream.Read(fileData, 0, fileData.Length);
            stream.Close();
            return fileData;
        }

  

posted @ 2012-10-24 13:26  白云任去留  阅读(15494)  评论(14编辑  收藏  举报