View :
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>新增演員資料</legend>
<div class="editor-label">
名稱
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
頭像
</div>
<div class="editor-field">
<img id="preview" src="#" style="width: 100px; height: 100px;" onerror="imgUserAvatarError(this)" />
<div class="fileUpload btn btn-primary">
<span>Upload</span>
<input type="file" class="upload" name="Avatar" id="Avatar" accept="image/*" onchange="PreviewImage();" />
</div>
@Html.ValidationMessageFor(model => model.Avatar)
</div>
<p>
<button type="submit" class="btn btn-purple no-border"><i class="icon-save bigger-160"></i>新增</button>
</p>
</fieldset>
}
* Html.BeginForm 要設定 object htmlAttributes 為 new { enctype = "multipart/form-data" }
Style :
<style>
.fileUpload {
position: relative;
overflow: hidden;
margin: 10px;
}
.fileUpload input.upload {
position: absolute;
top: 0;
right: 0;
margin: 0;
padding: 0;
font-size: 20px;
cursor: pointer;
opacity: 0;
filter: alpha(opacity=0);
}
</style>
JavaScript :
<script>
// 預覽圖片
function PreviewImage() {
var oFReader = new FileReader(); // HTML5 File API
oFReader.readAsDataURL(document.getElementById("Avatar").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("preview").src = oFREvent.target.result;
};
};
// 載入圖片失敗時, 使用預設圖片
function imgUserAvatarError(image) {
image.src = '@Url.Content("~/Images/nobody.jpg")';
return true;
}
</script>
* imgUserAvatarError 這個js function 要放在網頁頂端 (在預覽圖的img元素render之前)
Controller :
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Actor actor, HttpPostedFileBase Avatar)
{
_db.Actor.Add(actor);
_db.SaveChanges();
// 更新圖片
string picName = null;
var folderPath = HttpContext.Server.MapPath("~/Uploads/ActorAvatar"); // 存放路徑
if (!System.IO.Directory.Exists(folderPath)) // 路徑不存在先新增一個
{
System.IO.Directory.CreateDirectory(folderPath);
}
if (Avatar != null && Avatar.ContentLength > 0)
{
string ext = System.IO.Path.GetExtension(Avatar.FileName); // 取得副檔名
picName = "acotor_" + actor.Id + ext; // 重新命名圖片
var path = System.IO.Path.Combine(folderPath, picName);
Avatar.SaveAs(path);
}
return RedirectToAction("Index");
}
沒有留言:
張貼留言