MultipartFormDataContent GetMultipartFormDataContent2(IEnumerable <IUploadFileSource> uploadFiles) { var multipartFormDataContent = new MultipartFormDataContent(); int index = 0; foreach (var item in uploadFiles) { if (item.HasValue() && item.Available) { var uploadFile = item; var stream = uploadFile.OpenRead(); void ThrowUnsupportedUploadFileMediaType() // 未知的上传媒体类型 { stream?.Dispose(); multipartFormDataContent.Dispose(); // ↑ 释放未压缩的文件流 与 总内容(MultipartFormDataContent) 当前文件源不释放 var msg = $"Unsupported Upload File MediaType, filePath: {uploadFile.FilePath}, index: {index}"; logger.LogError(msg); throw new ApiResponseCodeException( ApiResponseCode.UnsupportedUploadFileMediaType, msg); } var needHandle = true; switch (uploadFile.UploadFileType) // 上传文件类型 { case UploadFileType.Image: // 图片 if (uploadFile.IsCompressed) // 文件源已压缩过 { if (string.IsNullOrEmpty(uploadFile.MIME)) // 无MIME,则检测 { if (FileFormat.IsImage(stream, out var format)) { if (format.IsAllow()) // 属于允许的格式,则不处理 { uploadFile.MIME = format.GetMIME(); needHandle = false; } } } else if (FileFormat.AllowImageMediaTypeNames.Contains(uploadFile.MIME)) { // 有MIME值,且在允许的范围内,则不处理 needHandle = false; } } break; //case UploadFileType.Voice: // 音频 // break; //case UploadFileType.Video: // 视频 // break; default: throw new ArgumentOutOfRangeException(nameof(uploadFile.UploadFileType), uploadFile.UploadFileType, null); } if (needHandle) { var result = helper.TryHandleUploadFile(stream, uploadFile.UploadFileType); if (!result.HasValue) // 处理失败 { ThrowUnsupportedUploadFileMediaType(); } else { stream.Dispose(); uploadFile.Dispose(); // ↑ 释放未压缩的文件流 与 文件源 uploadFile = new UploadFileSource { FilePath = result.Value.filePath, MIME = result.Value.mime, IsCompressed = true, IsCache = true, UploadFileType = uploadFile.UploadFileType, }; stream = uploadFile.OpenRead(); // 生成新的文件源 并 重新打开文件流 } } var content = new UploadFileContent(uploadFile, stream); if (string.IsNullOrWhiteSpace(uploadFile.FilePath)) { multipartFormDataContent.Add(content, "file"); } else { var fileName = Path.GetFileName(uploadFile.FilePath); multipartFormDataContent.Add(content, "file", fileName); } } index++; } if (!multipartFormDataContent.Any()) { throw new ApiResponseCodeException(ApiResponseCode.LackAvailableUploadFile); } return(multipartFormDataContent); }