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