首页 > 代码库 > c# api接口 文件处理
c# api接口 文件处理
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)); } }
c# api接口 文件处理
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。