I have mvc & angular application. I want to post image file to my web api.
my web api controller is:
public class UploadController : ApiController
{
public HttpResponseMessage Post()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if(httpRequest.Files.Count > 0)
{
var docfiles = new List<string>();
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/"+postedFile.FileName);
postedFile.SaveAs(filePath);
docfiles.Add(filePath);
}
result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
}
when im performing a request to post file via Postman i use this :
Headers = { Authorization : bearer ... , enctype : multipart/form-data }
and and the body request is form-data with key value pair (string , file), and this is successfully uploading my image.
what i try to send the image through my application (via angular $http):
var input = document.getElementById('uploadproductimage'); // FileList object
UploadImageFactory(input.files[0])
and this is my factory code:
return function (image) {
var result = $q.defer();
var formData = new FormData();
if (image) {
formData.append("uploadFile", image);
}
$http({
method: 'POST',
url: SessionService.apiUrl + '/api/upload',
data: formData,
header: { 'Authorization': 'Bearer ' + SessionService.getToken(), 'enctype': 'multipart/form-data' }
})
.success(function (response) {
console.log(response);
result.resolve(response);
})
.error(function (response) {
console.log(response);
result.reject(response);
});
return result.promise;
}
and my html input:
<input type="file" id="uploadproductimage" name="uploadproductimage" class="input-xlarge">
Thanks!