Hire ASP Developer
in ASP .NET

How to upload Image/Video/Any other file with other details in web api

by | 16 Dec 2013

To upload photo in mvc api controller the method is as below:
public System.Threading.Tasks.Task<Dictionary<string, dynamic>> UpdateProfileAndProfilePic()
{
HttpRequestMessage request = Request;
if (!request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(new
HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
}
var root = HttpContext.Current.Server.MapPath(“~/Uploads/ProfilePicture”);
var provider = new MultipartFormDataStreamProvider(root);
string UserId = string.Empty;
var task = request.Content.ReadAsMultipartAsync(provider).
ContinueWith(o =>
{
foreach (var key in provider.FormData.AllKeys)
{
var values = provider.FormData.GetValues(key);
if (values != null)
foreach (var val in values)
{
if (string.Equals(key, “UserId”,
StringComparison.OrdinalIgnoreCase))
{
if (!string.IsNullOrEmpty(Convert.ToString(val)))
UserId = Convert.ToInt32(val);
}
break;
}
}
if (UserId > 0)
{
if (provider.FileData.Count != 0)
{
File upload logic…
}
}
});
return task;
}

Sometimes the situation occurs when the photo uploading and insert is not mandatory but other details need to insert into the database at that time this function will work with some changes. When passing parameters, send blank multipart data(with no file) and put the condition after getting value parameter

if (provider.FileData.Count != 0)
{
Photo upload logic
}
Insert into database logic

Leave a Reply