2015-05-07 31 views
2

我正尝试在ASP MVC5项目中创建用户个人资料图片。我添加了一个名为changepicture.cshtml的页面,并显示当前用户的图片。显示上传到服务器的图片

我有一个上传功能,将拍摄人像hank.jpg上传的图片,并将其重命名为users_id.jpg

例如:

System.Data.Entity.DynamicProxies.ApplicationUser_9C8230B38B954135385F2B0311EAC02ED8B95C4D504F8424BA3ED79B37F0AAAF.jpg

我想通过抓住有用户ID和添加到显示每个用户在页面个体图像。 jpg,我该怎么做?

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(); 
} 
+0

你的路径应该是'Request.Files [upload] .SaveAs(Path.Combine(path,user.Id +“.jpg”));'。我不是100%哪一部分是问题?显示图片或使用用户标识保存图片作为文件名的一部分? –

+0

我的问题是显示这个上传的文件。 SpruceTips

回答

3

您正在为您的文件得到一个时髦的类型的名称,因为你正试图投整个类(对象)的字符串。另外,如果你想命名文件“UserId.jpg”,你的代码做了比它应该做的更多的工作。

这条线:

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

可以简化为这条线:

var userId = User.Identity.GetUserId(); 

这将使您的最终代码:

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(); 
} 

你可以摆脱用户id的完全变量,并将您的SaveAs方法更新为

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

另外 - 你真的应该装饰这个ActionResult与<HttpPost>属性,因为它应该只是处理表单的POST并不与GET请求相关联。

+0

我做了这个改变,但我怎么会抓住cshtml页面中的userid并显示图片? – SpruceTips

+1

完全相同的方式。 ''。或者,计算控制器中图像的url,并通过View Model将其传递给视图。 –

+0

有了这个我得到错误没有定义GetUserId(),是否需要添加使用此功能? – SpruceTips