2

I trying to create user profile page on MVC4 web application.

On the userprofile page there is an image <img /> tag to display profile photo. Just below the image, there are "browse", "upload" buttons for the user to browse and upload photo. On clicking upload button, it should upload the photo to SQL Server and show the image on the profile page.

I am able to upload photo and gets saved to SQL Server table. Now I want to retrieve the photo from SQL Server table to the profile page.

Here is my User profile page /.cshtml page (razor view )

@model MvcSamples.Models.UserPicModel

@{

    ViewBag.Title = "PersonalInfo";
}

<h2>PersonalInfo</h2>

<form action="/UserDetails/PersonalInfo"  method="post" enctype="multipart/form-data">
        <img src="" alt="ProfilePhoto" />
    <label for="photo">Photo:</label>
    <input type="file" name="photo" id="photo" />
    <input type="submit" value="Upload" />

</form>

This is the code I am using to retrieve photo back from the SQL Server table. Note that the photo is retrieved from db as byte[]

byte[] barrImg = usr.GetProfilePhoto(id);

When I debug, I can see the photo is retrieved to "barImg".

My question 1 : from here how can I get this to <img src="" alt="ProfilePhoto" /> so that it will show up the actual photo on the profile page?

Question 2: can someone suggest any better alternatives suggestions /samples/pointers to achieve the same functionality involving Jquery/Ajax /javascript

Thank you in advance

1 Answer 1

3

You can use FileResult, to send binary data to response.

public FileResult GetProfileImage(int id)
{
    var usr = new Whatever();
    byte[] barrImg = usr.GetProfilePhoto(id);
    return File(barrImg, "image/png");
}

You can use it as,

 <img src="@Url.Action("GetProfileImage", "Controller", new { id = 5})"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.