普通WebApi上传文件
#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 上传文件
.Net Core WebApi上传文件
using Microsoft.AspNetCore.Mvc; namespace CoreWebApiTest.Controllers { [ApiController] [Route("[controller]/[action]")] public class UploadTestController : ControllerBase { private readonly IWebHostEnvironment env; public UploadTestController(IWebHostEnvironment env) { this.env = env; } [HttpPost] public JsonResult UploadImg1() { //http://192.168.9.24:28543/UploadTest/UploadImg1 var webRootPath = this.env.ContentRootPath;//获取项目路径 var filePath = $"UploadFile\\"; var dirPath = Path.Combine(webRootPath, filePath); //D:\Demos\ConsoleApp1\CoreWebApiTest\UploadFile\ if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } var files = HttpContext.Request.Form.Files; foreach (var file in files) { var fname = file.FileName; var fileExtension = Path.GetExtension(file.FileName);// 文件后缀 var fileSize = file.Length;// 文件大小 1024 * 1024 * 10 = 10M using (FileStream fs = System.IO.File.Create(dirPath + fname)) { file.CopyTo(fs); fs.Flush(); } } return new JsonResult(new { Success = true, Message = "上传成功" }); } } }
.Net Core WebApi上传文件,发送请求方法
//控制台程序 string path = Path.Combine(AppContext.BaseDirectory, "img.png"); string fileName = Path.GetFileName(path); //文件转byte[] using FileStream fileStream = File.OpenRead(path); long byteLen = fileStream.Length; byte[] fileBytes = new byte[byteLen]; fileStream.Read(fileBytes, 0, (int)byteLen); //填充图片文件二进制字节 var fileContent = new ByteArrayContent(fileBytes); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "file", FileName = fileName }; var content = new MultipartFormDataContent(); content.Add(fileContent); string url = "http://192.168.9.24:28543/UploadTest/UploadImg1"; var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url); httpRequestMessage.Content = content; var httpClient = new HttpClient(); var httpResponseMessage = httpClient.SendAsync(httpRequestMessage).Result; if (httpResponseMessage.IsSuccessStatusCode) { using var contentStream = httpResponseMessage.Content.ReadAsStreamAsync().Result; using StreamReader sw = new StreamReader(contentStream); string res = sw.ReadToEnd(); }