Update-.net core 2.0 +
With the .net core, you can use the new IFormFile interface to load both the image and properties in a single post. For instance:
[HttpPost("content/upload-image")] public async Task<IActionResult> UploadImage(MyFile upload)
The MyFile class might look like this:
public class MyFile { public string userId { get; set; } public IFormFile File { get; set; }
You can access properties and file as follows:
var file = upload.File
To save / save the file to disk, you can do the following:
using (var stream = new FileStream(path, FileMode.Create)) { await file.File.CopyToAsync(stream); }
.NET Framework
Yes it. Depending on the client platform you are using, you can configure your web API for Content Type-Multipart , and then do something like:
[HttpPost] [Route("content/upload-image")] public async Task<HttpResponseMessage> Post() { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); }
Define and configure the directory in which your image will be saved.
var root = HttpContext.Current.Server.MapPath("~/Content/Images/"); if (!Directory.Exists(root)) { Directory.CreateDirectory(root); }
Install StreamProvider and try to get the model data that you mentioned in JSON format .
var streamProvider = new MultipartFormDataStreamProvider(root); var result = await Request.Content.ReadAsMultipartAsync(streamProvider); if (result.FormData["model"] == null) { throw new HttpResponseException(HttpStatusCode.BadRequest); }
Now access the files in the request.
try {
source share