How I can upload Image File via ASP.NET Web API?
I have an input tag in File mode and it posted to API, how I can save it to server folder?
I tried this code but it doesn't worked:
private void UploadWholeFile(HttpRequestBase request)
{
for (int i = 0; i < request.Files.Count; i++)
{
var file = request.Files[i];
var ext = new FileInfo(file.FileName).Extension;
var fullPath = Path.Combine(StorageRoot, Path.GetFileName(Guid.NewGuid() + ext));
file.SaveAs(fullPath);
}
}
WebApi supports deserializing JSON array, so that you can receive bytes by declaring with
byte[]
.The following example will show how to upload image:
In your controller. Writing image to disk:
HttpContext.Current.Server.MapPath("~/")
will give the internal path of server running.Request.RequestUri.Host
returns the hostname.To send image from browser
In HTML:
Upload method for AngularJS:
You can simply convert your image to a Base64String then post it as a StringContent.
bodyRequest on my code is the class/Model value to be converted to string
using Json.Serialize(model) which also contains your image System.Convert.ToBase64String(imageBytes[]) as its property.
If your API only allows one image at a time,
System.Web.Helpers.WebImage
may help. Just make sure that a filename is included.------WebKitFormBoundaryzrmNUJnUirtKajVF Content-Disposition: form-data; name="image"; filename="IMG_3321.JPG" Content-Type: image/jpeg
------WebKitFormBoundaryzrmNUJnUirtKajVF--
Set this code (taken from http://www.c-sharpcorner.com/uploadfile/fc9f65/uploading-a-file-with-web-api-and-entity-framework-using-aja/) on the WEB API Post Controller:
On your UWP application, set the following method:
You call your method as follows:
Hey, let me know if it works for you!! Happy to help! :)
You Can Use This Sample To Upload Image In Web Api.
First create
ImageWriterHelper
to check the file formatThen you should create class for saving image
Next create class
ImageResizeHelper
to resize the imageAt the end create action In Controller
I Used constructor injection for creating an instance of classes
please see this link: Uploading Image To Server Using Web API 2.0
Here i have described the whole process to upload the image in web api