WebApi上傳文件

 

WebApi上傳文件json

#region 上傳文件
        /// <summary>
        /// 經過multipart/form-data方式上傳文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<HttpResponseMessage> PostFile()
        {
            MessagesDataCodeModel json = new MessagesDataCodeModel(false, "無效參數", 401);

            try
            {
                // 是否請求包含multipart/form-data。
                if (!Request.Content.IsMimeMultipartContent())
                {
                    logger.Error("上傳格式不是multipart/form-data");
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                string root = HttpContext.Current.Server.MapPath("/UploadFiles/");
                if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/UploadFiles/")))
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/UploadFiles/"));
                }

                var provider = new MultipartFormDataStreamProvider(root);

                StringBuilder sb = new StringBuilder(); // Holds the response body

                // 閱讀表格數據並返回一個異步任務.
                await Request.Content.ReadAsMultipartAsync(provider);

                // 如何上傳文件到文件名.
                foreach (var file in provider.FileData)
                {
                    string orfilename = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"');
                    FileInfo fileinfo = new FileInfo(file.LocalFileName);
                    //sb.Append(string.Format("Uploaded file: {0} ({1} bytes)\n", fileInfo.Name, fileInfo.Length));
                    //最大文件大小 
                    //int maxSize = Convert.ToInt32(SettingConfig.MaxSize);
                    if (fileinfo.Length <= 0)
                    {
                        json.Success = false;
                        json.Msg = "請選擇上傳文件";
                        json.Code = 301;
                    }
                    else if (fileinfo.Length > ConfigHelper.MaxFileSize)
                    {
                        json.Msg = "上傳文件大小超過限制";
                        json.Code = 302;
                    }
                    else
                    {
                        string fileExt = orfilename.Substring(orfilename.LastIndexOf('.'));
                        //定義容許上傳的文件擴展名 
                        //String fileTypes = SettingConfig.FileTypes;
                        //if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
                        //{
                        //    json.Msg = "圖片類型不正確";
                        //    json.Code = 303;
                        //}
                        //else
                        //{
                        //String ymd = DateTime.Now.ToString("yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo);
                        //String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo);

                        fileinfo.CopyTo(Path.Combine(root, fileinfo.Name + fileExt), true);
                        json.Success = true;
                        json.Msg = "操做成功";
                        json.Code = 200;
                        sb.Append("/UploadFiles/" + fileinfo.Name + fileExt);
                        json.Data = sb.ToString();
                        //}
                    }
                    fileinfo.Delete();//刪除原文件
                }
            }
            catch (System.Exception e)
            {
                json.Success = false;
                json.Msg = "服務器無響應";
                json.Code = 500;
                logger.Error("PostFile()服務器錯誤", e);
            }
            return ToJsonTran.ToJson(json);
        }
        #endregion 上傳文件
相關文章
相關標籤/搜索