Google Code Prettify

[Javascript][MVC] Input file 選取檔案後預覽圖片

選取一個圖片檔案後,直接進行預覽


<script>
function InputLoadImageToBindImageElement(inputEl, imgEl) {
 
    if (inputEl.files && inputEl.files[0]) {
        var reader = new FileReader();
 
        reader.onload = function (e) {
            $(imgEl).attr('src', e.target.result);
        }
 
        reader.readAsDataURL(inputEl.files[0]);
    }
}
</script>




HTML

<img src="" id="image1" />
<input type="file" name="name" id="iptImage1" value="" />





呼叫


<script>
$("#iptImage1").change(function () {
          InputLoadImageToBindImageElement(this, $('#image1'));
});
</script>



注意:
本文中的 Script 都必須放在 Form 的後面,或者乾脆就放在頁面的最下方,以免找不到 Input 而報錯。






MVC 中可用下面的方法叫用


@model WebServiceTest.Models.UploadFileInfo

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>
<div>@ViewBag.Message</div>
@using(Html.BeginForm("Index", "FileUpload", 
       new { ReturnUrl = ViewBag.ReturnUrl }, 
       FormMethod.Post, 
       new { @class = "form-inline", role = "form", enctype = "multipart/form-data" })) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()
    <input id="FileName" multiple="multiple" name="FileName" type="file" />
    <img id="image1" src="" />
    <input id="btnSubmit" name="btnSubmit" type="submit" value="Submit" />
}

@section  scripts{
    <script>
        $("#FileName").change(function () {
            InputLoadImageToBindImageElement(this, $('#image1'));
        });
        function InputLoadImageToBindImageElement(inputEl, imgEl) {
            if (inputEl.files && inputEl.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $(imgEl).attr('src', e.target.result);
                }
                reader.readAsDataURL(inputEl.files[0]);
            }
        }
    </script>
}