普通WebApi上传文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | #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上传文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | 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上传文件,发送请求方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | //控制台程序 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(); } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】