显示上传到服务器的图片

时间:2015-05-07 00:09:40

标签: c# asp.net-mvc

我正在尝试在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();
}

1 个答案:

答案 0 :(得分: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();
}

您可以完全删除userId变量,并将SaveAs方法更新为

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

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

相关问题