I am trying to upload an image and display it in my application. I am working in AngularJS, MVC and Web APi. My Image uploads successfully to a folder.
Issue is: After uploading I send back relative path as Http response and set it to my controller $scope property which in turn I want to bind with img src. I am not sure if this is proper way to do it or not. Please guide is this wrong or what I am doing wrong.
My view is:
<div class="profilePic">
<img src="@Url.Content(UserDetails.PrflPic)" alt="Sample Image" />
</div>
<input type="file" valid-file upload="uploadFile(file)" ng-model="file">
Here "UserDetails.PrflPic" is my $scope property that I want to use some how. But, I cannot do this because Url.Content takes string only. I tried this @Url.Content({{UserDetails.PrflPic}}) which also is not fine.
My Controller Method is:
$scope.uploadFile = function (file) {
var PromiseData = UserService.uploadProfilePicture(file);
PromiseData.then(function (Response) {
alertify.alert('Image uploaded sucessfully');
$scope.UserDetails.PrflPic = Response.data;
$scope.$apply();
}, function (Error) {$scope.$apply();
alertify.alert('Some issue occurred while saving picture');
});
}
File Upload Api as:
public IHttpActionResult Post()
{
var httpRequest = HttpContext.Current.Request;
// Check if files are available
if (httpRequest.Files.Count > 0)
{
var postedFile = httpRequest.Files[0];
var path = System.Web.Hosting.HostingEnvironment.MapPath("~/UserProfilePic/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
// Fetch the File Name.
string fileName = Path.GetFileName(postedFile.FileName);
// Save the File.
postedFile.SaveAs(path + fileName);
var ImgLoc = "~/UserProfilePic/" + fileName;
return Content(HttpStatusCode.OK, ImgLoc);
}
else
{
return BadRequest("No files to upload.");
}
}
2
Answers
Please try this
The
ng-src
directive allows you to bind the src attribute.