c# api接口 文件处理

时间:2021-07-03 03:56:55

/// <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)); } }