SpruceTips
SpruceTips

Reputation: 225

Display a picture uploaded to the server

I am trying to create a user profile picture in a ASP MVC5 project. I have added a page that is called changepicture.cshtml and will display the current user's picture.

I have an upload function that will take a picture someone uploads like hank.jpg and rename it to that users_id.jpg.

For example:

System.Data.Entity.DynamicProxies.ApplicationUser_9C8230B38B954135385F2B0311EAC02ED8B95C4D504F8424BA3ED79B37F0AAAF.jpg

I would like to display each users individual picture in the page by grabbing there user id and adding .jpg, how would I do this?

changepicture.cshtml

@model KidRoutineLogging.Models.ChangePictureViewModel
@{
    ViewBag.Title = "Change Picture";
}

<h2>@ViewBag.Title.</h2>

<h4>Your Current Picture  : @Html.ViewBag.CurrentPicture</h4>

<img src="@Url.Content("~/uploads/hank.jpg")" />

<br />
<br />
@using (Html.BeginForm("", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

    <input type="file" name="FileUpload1" /><br />
    <input type="submit" name="Submit" id="Submit" value="Upload" />
}


@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

HomeController.cs

public async Task<ActionResult> Index()
{
    foreach (string upload in Request.Files)
    {
        var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

        string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
        //string filename = Path.GetFileName(Request.Files[upload].FileName);
        //Request.Files[upload].SaveAs(Path.Combine(path, filename));

        Request.Files[upload].SaveAs(Path.Combine(path, user + ".jpg"));
    }
    return View();
}

Upvotes: 2

Views: 99

Answers (1)

Tommy
Tommy

Reputation: 39807

You are getting a funky-typed name for your file because you are attempting to cast an entire class (object) to string. Additionally, if you are wanting to name the file "UserId.jpg", your code is doing more work than it should.

This line:

var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

Can be simplified to this line:

var userId = User.Identity.GetUserId();

That would leave your final code as:

public async Task<ActionResult> Index()
{
    foreach (string upload in Request.Files)
    {
        var userId = User.Identity.GetUserId();
        string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
        Request.Files[upload].SaveAs(Path.Combine(path, userId + ".jpg"));
    }
    return View();
}

You could get rid of the userId variable completely, and update your SaveAs method to

Request.Files[upload].SaveAs(Path.Combine(path, User.Identity.GetUserId()+ ".jpg"));

Also - you really should decorate this ActionResult with the <HttpPost> attribute since it should only be handling the POSTing of the form and not associated with a GET request.

Upvotes: 3

Related Questions