我希望能够在上传文件(图像)之前预览它。预览操作应该在浏览器中全部执行,而不使用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=“”/>

其他回答

使用纯JavaScript以可重用的方式在单个函数中预览多个文件和单个文件

函数imagePreviewFunc(即,previewerId){let files=that.filepreviewerId.innerHTML=“”//重置图像预览元素for(假设i=0;i<files.length;i++){let imager=document.createElement(“img”);imager.src=URL.createObjectURL(文件[i]);previewerId.append(成像器);}}<input accept=“image/*”type='file'id=“imageInput_1”onchange=“imagePreviewFunc(this,imagePreview_1)”/><div id=“imagePreview_1”>此分区用于单图像预览</div><hr/><input class=“form control”accept=“image/*”type='file'id=“imageInput_2”multiple=“true”onchange=“imagePreviewFunc(this,imagePreview_2)”/><div id=“imagePreview_2”>此div用于多图像预览</div>

https://stackoverflow.com/a/59985954/8784402

ES2017方式

//将文件转换为base64 url常量readURL=文件=>{return new Promise((res,rej)=>{const reader=新文件读取器();reader.onload=e=>res(e.target.result);reader.oneror=e=>rej(e);reader.readAsDataURL(文件);});};//用于演示const fileInput=document.createElement('input');fileInput.type=“文件”;const img=document.createElement('img');img.attributeStyleMap.set(“最大宽度”,“320px”);document.body.appendChild(fileInput);document.body.appendChild(img);常量预览=异步事件=>{const file=event.target.files[0];const-url=等待读取url(文件);img.src=url;};fileInput.addEventListener('change',预览);

使用jquery预览多个文件

$(文档).ready(函数){$('#image').change(function(){$(“#frames”).html(“”);对于(var i=0;i<$(this)[0].files.length;i++){$(“#frames”).append('<img src=“'+window.URL.createObjectURL(this.files[i])+'”width=“100px”height=“100px“/>');}});});<head><script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js“></script></head><body><input-type=“file”id=“image”name=“image[]”多个/><br/><div id=“frames”></div></body>

这里有一种在上传前使用纯javascript预览图像的简单方法;

//profile_change is the id of the input field where we choose an image
document.getElementById("profile_change").addEventListener("change", function() {

//Here we select the first file among the selected files.
const file = this.files[0];

/*here i used a label for the input field which is an image and this image will 
  represent the photo selected and profile_label is the id of this label */
const profile_label = document.getElementById("profile_label");

//Here we check if a file is selected
if(file) {
    //Here we bring in the FileReader which reads the file info. 
    const reader = new FileReader();
    
    /*After reader loads we change the src attribute of the label to the url of the 
    new image selected*/
    reader.addEventListener("load", function() {
        dp_label.setAttribute("src", this.result);
    })

    /*Here we are reading the file as a url i.e, we try to get the location of the 
    file to set that as the src of the label which we did above*/
    reader.readAsDataURL(file);

}else {
    //Here we simply set the src as default, whatever you want if no file is selected.
    dp_label.setAttribute("src", "as_you_want")
}
});

这里是HTML;

<label for="profile_change">
            <img title="Change Profile Photo" id="profile_label" 
             src="as_you_want" alt="DP" style="height: 150px; width: 150px; 
               border-radius: 50%;" >
</label>
<input style="display: none;" id="profile_change" name="DP" type="file" class="detail form-control">

单层解决方案:

下面的代码使用对象URL,在查看大型图像时,它比数据URL更有效(数据URL是包含所有文件数据的巨大字符串,而对象URL只是引用内存中文件数据的短字符串):

<img id=“blah”alt=“your image”width=“100”height=“100”/><输入类型=“文件”onchange=“document.getElementById('blah').src=window.URL.createObjectURL(this.files[0])”>

生成的URL如下:

blob:http%3A//localhost/7514bc74-65d4-4cf0-a0df-3de016824345