WebAPI圖片上傳

public Task<HttpResponseMessage> PostFormData()
        {
            // Check if the request contains multipart/form-data.
            // 檢查該請求是否含有multipart/form-data
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string root = HttpContext.Current.Server.MapPath("~/userImage");
            var provider = new MultipartFormDataStreamProvider(root);

            // Read the form data and return an async task.
            // 讀取表單數據,並返回一個async任務
            var task = Request.Content.ReadAsMultipartAsync(provider).
                ContinueWith<HttpResponseMessage>(t =>
                {
                    if (t.IsFaulted || t.IsCanceled)
                    {
                        Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                    }

                    // This illustrates how to get the file names.
                    // 如下描述瞭如何獲取文件名
                    foreach (MultipartFileData file in provider.FileData)
                    {
                        //新文件夾路徑
                        string newRoot = root + "\\" + provider.FormData.GetValues(1)[0].ToString();
                        if (!Directory.Exists(newRoot))
                        {
                            Directory.CreateDirectory(newRoot);
                        }
                        Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                        Trace.WriteLine("Server file path: " + file.LocalFileName);
                        if (File.Exists(file.LocalFileName)) 
                        {
                            //原文件名稱
                            string fileName = file.Headers.ContentDisposition.FileName.Substring(1, file.Headers.ContentDisposition.FileName.Length - 2);
                            //新文件名稱   隨機數
                            string newFileName = provider.FormData.GetValues(0)[0] + "." + fileName.Split(new char[] { '.' })[1];
                            File.Move(file.LocalFileName, newRoot + "\\" + newFileName);
                        }
                    }
                    return Request.CreateResponse(HttpStatusCode.OK);
                });

            return task;
        }

 

 [HttpPost]
        public async Task<Dictionary<string, string>> Post(int id = 0)
        {

            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            Dictionary<string, string> dic = new Dictionary<string, string>();
            string root = HttpContext.Current.Server.MapPath("~/App_Data");//指定要將文件存入的服務器物理位置
            var provider = new MultipartFormDataStreamProvider(root);
            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);//獲取上傳文件在服務上默認的文件名
                }//TODO:這樣作直接就將文件存到了指定目錄下,暫時不知道如何實現只接收文件數據流但並不保存至服務器的目錄下,由開發自行指定如何存儲,好比經過服務存到圖片服務器
                foreach (var key in provider.FormData.AllKeys)
                {//接收FormData
                    dic.Add(key, provider.FormData[key]);
                }
            }
            catch
            {
                throw;
            }
            return dic;
        }

 原文地址:http://blog.csdn.net/starfd/article/details/45393089服務器

相關文章
相關標籤/搜索