2014年1月27日 星期一

asp.net mvc + html5 上傳圖片

View :

@using (Html.BeginForm(nullnullFormMethod.Postnew { 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="width100pxheight100px;" 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 {
        positionrelative;
        overflowhidden;
        margin10px;
    }
 
        .fileUpload input.upload {
            positionabsolute;
            top0;
            right0;
            margin0;
            padding0;
            font-size20px;
            cursorpointer;
            opacity0;
            filteralpha(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 actorHttpPostedFileBase 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(folderPathpicName);
                Avatar.SaveAs(path);
            }
            return RedirectToAction("Index");
        }



沒有留言: