解决方法
更新 – .net核心2.0
使用.net核心,您可以利用新的IFormFile接口在同一帖子中上传图像和属性.例如:
[HttpPost("content/upload-image")] public async Task<IActionResult> UploadImage(MyFile upload)
MyFile类看起来像:
public class MyFile { public string userId { get; set; } public IFormFile File { get; set; } // Other properties }
var file = upload.File // This is the IFormFile file var param = upload.userId // param
要将文件保留/保存到磁盘,您可以执行以下操作:
using (var stream = new FileStream(path,FileMode.Create)) { await file.File.CopyToAsync(stream); }
.NET Framework
是的.根据您正在使用的客户端框架,您可以为内容类型 – 多部件配置Web API,然后执行以下操作:
[HttpPost] [Route("content/upload-image")] public async Task<HttpResponseMessage> Post() { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } // enter code here }
定义并设置保存图像的目录.
var root = HttpContext.Current.Server.MapPath("~/Content/Images/"); if (!Directory.Exists(root)) { Directory.CreateDirectory(root); }
设置StreamProvider并尝试获取模型数据,这是您提到的JSON.
var streamProvider = new MultipartFormDataStreamProvider(root); var result = await Request.Content.ReadAsMultipartAsync(streamProvider); if (result.FormData["model"] == null) { throw new HttpResponseException(HttpStatusCode.BadRequest); }
现在访问请求中的文件.
try { // Deserialize model data to your own DTO var model = result.FormData["model"]; var formDto = JsonConvert .DeserializeObject<MyDto>(model,new IsoDateTimeConverter()); var files = result.FileData.ToList(); if (files != null) { foreach (var file in files) { // Do anything with the file(s) } } }