N. Brown
N. Brown

Reputation: 3

Uploading and displaying multiple images from database in MVC

I am using ASP.NET MVC and I am trying to upload multiple images to a database and then display them in a view. I believe the upload process is working however when I try to display the images only the alternative text is being shown and a resource cannot be found error in the Chrome debugging.

This is how my image is displayed in my view

@model IList<InspectionPhoto>

<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h4 class="modal-title" id="myModalLabel">Photo Management</h4>
</div>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="modal-body">
        <div class="form-horizontal">

            @if (Model.Count > 0)
            {
                <div class="row">
                    @for (var i = 0; i < Model.Count(); i++)
                    {
                        <div class="row">
                            <div class="col-md-6">
                                <img src="@Url.Action( "ShowPhoto", "Inspection", new { id = Model[i].PhotoID } )" alt="Image not available" />
                            </div> 
 //continues

Show Photo method:

public Bitmap ShowPhoto(int id)
{
    InspectionPhoto image = db.InspectionPhotoes.Find(id);
    var result = (Bitmap)((new ImageConverter()).ConvertFrom(image.ImageBytes));
    return result;
}

The show photo method is in my Inspections controller because the Photo view is a modal partial view that is show when a button is clicked in the inspection view.

Any help would be greatly appreciated. Please let me know if more information is needed.

Upvotes: 0

Views: 2901

Answers (3)

Pooria
Pooria

Reputation: 157

I think you should return FileContent

    public FileContentResult GetImage(int id)
    {
        InspectionPhoto image = db.InspectionPhotoes.Find(id);
        byte[] byteArray = image.ImageBytes ;
        return byteArray != null
            ? new FileContentResult(byteArray, "image/jpeg")
            : null;
    }

Upvotes: 0

Ibrahim Khan
Ibrahim Khan

Reputation: 20750

ShowPhoto returns Bitmap but should return File like following. If your your image is saved correctly then following should work fine.

public ActionResult ShowPhoto(int id)
{
    InspectionPhoto image = db.InspectionPhotoes.Find(id);
    byte[] result = image.ImageBytes;
    return File(result, "image/png");
}

Upvotes: 2

Jonathon Chase
Jonathon Chase

Reputation: 9714

Your ShowPhoto method is returning a Bitmap, which you are attempting to write in is the html's img src tag, which is expecting a url-string. You should modify the ShowPhoto function to instead return the url associated with the image that has been uploaded.

Upvotes: 0

Related Questions