c# 通过接口上传文件到服务器(IFormFile)
注意:客户端上传文件到服务器,服务器端需要定义接收方法处理文件
客户端:ASP.NET Core 框架的API接口
服务端:非Core 框架的API接口
客户端代码
//控制器 [HttpPost("ShipmentReportUploadFile")] [ProducesResponseType(StatusCodes.Status200OK)] public async Task<AppSrvResult<string>> ShipmentReportUploadFile([FromForm] FileUploadDto input) => await _salesService.ShipmentReportUploadFile(input.file, input.FileCode); public class FileUploadDto { public IFormFile file { get; set; } //自定义需要的参数 public string? FileCode { get; set; } = ""; } //省略调用.. //service实现
/// <summary>
///
/// </summary>
/// <param name="url">调用的接口地址</param>
/// <param name="file">文件</param>
/// <param name="FileCode"></param>
/// <returns></returns>
private async Task<string> PostFormDataAsync(string url, IFormFile file, string FileCode) { if (file == null || file.Length == 0) { return "未上传文件"; } // 使用MemoryStream来读取文件内容 using (var memoryStream = new MemoryStream()) { await file.CopyToAsync(memoryStream); byte[] fileBytes = memoryStream.ToArray(); // 调用ASP.NET(非Core)框架的API接口地址拼接 var apiUrl = _configuration.GetSection("ErpApi").GetValue<string>("BaseUrl") + url; using (var client = new HttpClient()) { using (var content = new MultipartFormDataContent()) { // 添加文件到MultipartFormDataContent var fileContent = new ByteArrayContent(fileBytes); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); content.Add(fileContent, "file", file.FileName); // 添加其他表单数据 int index = file.FileName.LastIndexOf("."); if (index == -1) return "文件类型未知,上传失败"; string fileType = file.FileName.Substring(index, file.FileName.Length - index); content.Add(new StringContent(file.FileName), "FileName"); content.Add(new StringContent(fileType), "FileType"); if (!string.IsNullOrEmpty(FileCode)) content.Add(new StringContent(FileCode), "FileCode"); // 发送POST请求到ASP.NET API var response = await client.PostAsync(apiUrl, content); // 检查响应状态码并处理响应 if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsStringAsync(); return result.Replace("\"", ""); } else { return $"Upload failed. Status: {response.StatusCode}, Content: {response.Content}"; } } } } }
服务器端代码处理文件
[HttpPost] public async Task<string> HTTPPostFile() { //// 检查请求是否为 multipart/form-data 类型 //if (!Request.Content.IsMimeMultipartContent()) //{ // throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); //} // 设置文件保存路径 //string root = HttpContext.Current.Server.MapPath("~/Uploads"); string root = ConfigurationManager.AppSettings["FilePath"] + DateTime.Now.ToString("yyyy年MM月"); Directory.CreateDirectory(root); // 确保目录存在 // 使用 MultipartFormDataStreamProvider 解析请求,但不自动保存文件 var provider = new MultipartFormDataStreamProvider(root); try { // 异步读取请求内容 await Request.Content.ReadAsMultipartAsync(provider); // 获取其他表单数据 var formData = provider.FormData; var FileName = formData["FileName"]; var FileType = formData["FileType"]; var FileCode = formData["FileCode"]; var file = provider.FileData[0]; // 获取原始文件名(包含扩展名) string originalFileName = file.Headers.ContentDisposition.FileName.Trim('"'); // 生成自定义文件名 string customFileName = DateTime.Now.ToString("MMddHHmmssfff") + FileType; // 获取文件的完整保存路径 string filePath = Path.Combine(root, customFileName); // 将文件复制到新位置,并使用自定义文件名保存 File.Copy(file.LocalFileName, filePath, true); // 删除临时文件 File.Delete(file.LocalFileName); string fileCode = ""; if (string.IsNullOrEmpty(FileCode)) fileCode = db.Database.SqlQuery<string>("select convert(varchar(100),newid())").First(); else fileCode = FileCode; return fileCode; } catch (Exception ex) { return ex.Message; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)