.net mvc 实现上传头像功能
时间: 2023-08-12 13:16:49 浏览: 81
要在 .NET MVC 中实现上传头像功能,可以按照以下步骤进行:
1. 在 View 中添加一个表单,用于上传头像文件:
```
@using (Html.BeginForm("UploadAvatar", "User", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="avatarFile" />
<input type="submit" value="上传头像" />
}
```
2. 在 Controller 中添加一个 Action,用于处理上传头像文件的逻辑:
```
[HttpPost]
public ActionResult UploadAvatar(HttpPostedFileBase avatarFile)
{
if (avatarFile != null && avatarFile.ContentLength > 0)
{
var fileName = Path.GetFileName(avatarFile.FileName);
var path = Path.Combine(Server.MapPath("~/Content/Avatars"), fileName);
avatarFile.SaveAs(path);
}
return RedirectToAction("Index");
}
```
3. 在上述代码中,`HttpPostedFileBase` 类型的 `avatarFile` 参数表示上传的文件,`Path.GetFileName` 和 `Path.Combine` 方法用于获取文件名和保存路径,`Server.MapPath` 方法用于将相对路径转换为绝对路径,`avatarFile.SaveAs` 方法用于保存文件。
4. 在 `SaveAs` 方法执行成功后,文件就会被保存在 `~/Content/Avatars` 目录下(如果该目录不存在,需要先手动创建)。可以在 View 中使用以下代码来显示上传的头像:
```
@if (System.IO.File.Exists(Server.MapPath("~/Content/Avatars/avatar.jpg")))
{
<img src="@Url.Content("~/Content/Avatars/avatar.jpg")" />
}
```
上述代码中,`System.IO.File.Exists` 方法用于判断头像文件是否存在,`Url.Content` 方法用于获取头像文件的 URL。