我希望能够在上传文件(图像)之前预览它。预览操作应该在浏览器中全部执行,而不使用Ajax上传图像。

我该怎么做?


当前回答

这是我的代码。支持IE[6-9]、chrome 17+、firefox、Opera 11+、Maxthon3

函数previewImage(fileObj,imgPreviewId){var allowExtetion=“.jpg,.bmp,.gif,.png”//允许上载文件类型document.getElementById(“hfAllowPicSuffix”).value;var extention=fileObj.value.substring(fileObj.value.lastIndexOf(“.”)+1).toLowerCase();var browserVersion=window.navigator.userAgent.toUpperCase();如果(allowExtendition.indexOf(extention)>-1){if(fileObj.files){if(window.FileReader){var reader=新文件读取器();reader.onload=函数(e){document.getElementById(imgPreviewId).setAttribute(“src”,e.target.result);};reader.readAsDataURL(fileObj.files[0]);}否则如果(browserVersion.indexOf(“SAFARI”)>-1){警告(“不支持低于broswer的Safari6.0”);}}否则如果(browserVersion.indexOf(“MSIE”)>-1){如果(browserVersion.indexOf(“MSIE 6”)>-1){//ie6document.getElementById(imgPreviewId).setAttribute(“src”,fileObj.value);}其他{//ie[7-9]文件对象选择();fileObj.blur();var newPreview=文档.getElementById(imgPreviewId);newPreview.style.border=“实心1px#eeeeee”;newPreview.style.filter=“progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='”+document.selection.createRange().text+“')”;newPreview.style.display=“块”;}}否则如果(browserVersion.indexOf(“FIREFOX”)>-1){//FIREFOXvar firefoxVersion=parseFloat(browserVersion.toLowerCase().match(/frefox\/([\d.]+)/)[1]);如果(firefoxVersion<7){//firefox7以下document.getElementById(imgPreviewId).setAttribute(“src”,fileObj.files[0].getAsDataURL());}其他{//firefox7.0+document.getElementById(imgPreviewId).setAttribute(“src”,window.URL.createObjectURL(fileObj.files[0]));}}其他{document.getElementById(imgPreviewId).setAttribute(“src”,fileObj.value);}}其他{警报(“仅支持”+allowExtension+“后缀”);fileObj.value=“”//清除选定文件如果(browserVersion.indexOf(“MSIE”)>-1){文件对象选择();document.selection.clear();}}}函数更改文件(elem){//文件对象,预览img标记id预览图像(elem,'imagePreview')}<input-type=“file”id=“netBarBig”onchange=“changeFile(this)”/><img src=“”id=“imagePreview”style=“width:120px;height:80px;”alt=“”/>

其他回答

我已经制作了一个插件,由于互联网,它可以在IE 7+中生成预览效果,但几乎没有限制。我把它放进github页面,这样更容易获取

$(函数(){$(“input[name=file1]”).previewimage({div:“.preview”,imgwidth:180,高度:120});$(“input[name=file2]”).previewimage({div:“.preview 2”,imgwidth:90,高度:90});});.preview>div{显示:内联块;文本对齐:居中;}.preview2>div{显示:内联块;文本对齐:居中;}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js“></script><script src=“https://rawgit.com/andrewng330/PreviewImage/master/preview.image.min.js“></script>预览<div class=“preview”></div>预览2<div class=“preview2”></div><form action=“#”method=“POST”enctype=“multipart/form data”><input-type=“file”name=“file1”><input-type=“file”name=“file2”><input-type=“submit”></form>

function assignFilePreviews() {
    $('input[data-previewable=\"true\"]').change(function() {
        var prvCnt = $(this).attr('data-preview-container');
        if (prvCnt) {
            if (this.files && this.files[0]) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    var img = $('<img>');
                    img.attr('src', e.target.result);
                    img.error(function() {
                        $(prvCnt).html('');
                    });
                    $(prvCnt).html('');
                    img.appendTo(prvCnt);
                }
                reader.readAsDataURL(this.files[0]);
            }
        }
    });
}
$(document).ready(function() {
    assignFilePreviews();
});

HTML格式

<input type="file" data-previewable="true" data-preview-container=".prd-img-prv" />
<div class = "prd-img-prv"></div>

当选择了无效类型(例如pdf)的文件时,这也会处理这种情况

干净简单J小提琴

当您希望通过div或按钮间接触发事件时,这将非常有用。

<img id="image-preview"  style="height:100px; width:100px;"  src="" >

<input style="display:none" id="input-image-hidden" onchange="document.getElementById('image-preview').src = window.URL.createObjectURL(this.files[0])" type="file" accept="image/jpeg, image/png">

<button  onclick="HandleBrowseClick('input-image-hidden');" >UPLOAD IMAGE</button>


<script type="text/javascript">
function HandleBrowseClick(hidden_input_image)
{
    var fileinputElement = document.getElementById(hidden_input_image);
    fileinputElement.click();
}     
</script>

我编辑了@Ivan的答案,以显示“无预览可用”图像,如果它不是图像:

function readURL(input) {
    var url = input.value;
    var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
    if (input.files && input.files[0]&& (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('.imagepreview').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }else{
         $('.imagepreview').attr('src', '/assets/no_preview.png');
    }
}

默认Iamge

                @Html.TextBoxFor(x => x.productModels.DefaultImage, new {@type = "file", @class = "form-control", onchange = "openFile(event)", @name = "DefaultImage", @id = "DefaultImage" })
                @Html.ValidationMessageFor(model => model.productModels.DefaultImage, "", new { @class = "text-danger" })
                    <img src="~/img/ApHandler.png"  style="height:125px; width:125px" id="DefaultImagePreview"/>
            </div>

 <script>
    var openFile = function (event) {
        var input = event.target;

        var reader = new FileReader();
        reader.onload = function () {
            var dataURL = reader.result;
            var output = document.getElementById('DefaultImagePreview');
            output.src = dataURL;
        };
        reader.readAsDataURL(input.files[0]);
    };
</script>