1. 程式人生 > >c# api接口 文件處理

c# api接口 文件處理

request () sys text ask tel 獲取文件 substr tap

api接口 上傳文件

技術分享
    /// <summary>
        /// POST api/FileManager/PostFormData
        /// </summary>
        /// <returns></returns>
        [ActionName("PostFormData")]
        [HttpPost]
        public async 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(PortraitApp); 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); } return Request.CreateResponse(HttpStatusCode.OK); } catch (System.Exception e) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); } } /// <summary> /// POST api/FileManager/PostFormFile /// </summary> /// <returns></returns> [ActionName("PostFormFile")] [HttpPost] public IHttpActionResult PostFormFile() { try { if (!Directory.Exists(HttpContext.Current.Server.MapPath(PortraitApp))) { Directory.CreateDirectory(HttpContext.Current.Server.MapPath(PortraitApp)); } HttpFileCollection files = HttpContext.Current.Request.Files; string name = ""; foreach (string key in files.AllKeys) { HttpPostedFile file = files[key]; if (string.IsNullOrEmpty(file.FileName) == false) { int length = file.ContentLength; if (length>2097152) { throw new CustomException("上傳文件超過2M,請將上傳文件大小控制在2M內,謝謝"); } string extension = file.FileName.Substring(file.FileName.LastIndexOf(.)).ToLower(); if (extension!=".bmp"&& extension != ".jpg" && extension != ".jpeg" && extension != ".png") { throw new CustomException("上傳文件擴展名不正確,請上傳bmp,jpg,jpeg,png格式的圖片"); } name = DateTime.Now.ToStringByDatetime(DateTimeType.yyyyMMddHHmmss) + extension; //LoginVerifyModels usermodel = GetVerifyModel(); string username = GetVerifyString(); if (!string.IsNullOrEmpty(username)) { name = username + extension; } file.SaveAs(HttpContext.Current.Server.MapPath(PortraitApp) + name); } } return Json(Success(new { ImgPath = RetureTemp + name })); } catch (CustomException ce) { return Json(getException(ce.Message)); } catch (Exception ex) { return Json(getException(ex)); } }
View Code

c# api接口 文件處理