在上传之前预览图像

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

我怎么能这么做?

1625038 次浏览

imgInp.onchange = evt => {const [file] = imgInp.filesif (file) {blah.src = URL.createObjectURL(file)}}
<form runat="server"><input accept="image/*" type='file' id="imgInp" /><img id="blah" src="#" alt="your image" /></form>

LeassTaTT的答案在FF和Chrome等“标准”浏览器中运行良好。IE的解决方案存在,但看起来不同。这里跨浏览器解决方案的描述:

在超文本标记语言中,我们需要两个预览元素,img用于标准浏览器,div用于IE

超文本标记语言:

<img id="preview"src=""alt=""style="display:none; max-width: 160px; max-height: 120px; border: none;"/>
<div id="preview_ie"></div>

在CSS中,我们指定以下IE特定的东西:

css:

#preview_ie {FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)}

在超文本标记语言中,我们包括标准和IE特定的Javascript:

<script type="text/javascript">{% include "pic_preview.js" %}</script><!--[if gte IE 7]><script type="text/javascript">{% include "pic_preview_ie.js" %}</script>

pic_preview.js是LeassTaTT答案中的Javascript。将$('#blah')替换为$('#preview')并添加$('#preview').show()

现在是IE特定的Javascript(pic_preview_ie.js):

function readURL (imgFile) {var newPreview = document.getElementById('preview_ie');newPreview.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = imgFile.value;newPreview.style.width = '160px';newPreview.style.height = '120px';}

是的。适用于IE7、IE8、FF和Chrome。请在IE9中测试并报告。IE预览的想法是在这里找到的:http://forums.asp.net/t/1320559.aspx

http://msdn.microsoft.com/en-us/library/ms532969(v=vs.85). aspx

创建一个加载文件并触发自定义事件的函数如何。然后将侦听器附加到输入。这样我们就可以更灵活地使用文件,而不仅仅是用于预览图像。

/*** @param {domElement} input - The input element* @param {string} typeData - The type of data to be return in the event object.*/function loadFileFromInput(input,typeData) {var reader,fileLoadedEvent,files = input.files;
if (files && files[0]) {reader = new FileReader();
reader.onload = function (e) {fileLoadedEvent = new CustomEvent('fileLoaded',{detail:{data:reader.result,file:files[0]},bubbles:true,cancelable:true});input.dispatchEvent(fileLoadedEvent);}switch(typeData) {case 'arraybuffer':reader.readAsArrayBuffer(files[0]);break;case 'dataurl':reader.readAsDataURL(files[0]);break;case 'binarystring':reader.readAsBinaryString(files[0]);break;case 'text':reader.readAsText(files[0]);break;}}}function fileHandler (e) {var data = e.detail.data,fileInfo = e.detail.file;
img.src = data;}var input = document.getElementById('inputId'),img = document.getElementById('imgId');
input.onchange = function (e) {loadFileFromInput(e.target,'dataurl');};
input.addEventListener('fileLoaded',fileHandler)

可能我的代码不如一些用户好,但我认为你会明白的。在这里你可以看到一个示例

我编辑了@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');}}

是的。这是可能的。

Html

<input type="file" accept="image/*"  onchange="showMyImage(this)" /><br/><img id="thumbnil" style="width:20%; margin-top:10px;"  src="" alt="image"/>

JS

 function showMyImage(fileInput) {var files = fileInput.files;for (var i = 0; i < files.length; i++) {var file = files[i];var imageType = /image.*/;if (!file.type.match(imageType)) {continue;}var img=document.getElementById("thumbnil");img.file = file;var reader = new FileReader();reader.onload = (function(aImg) {return function(e) {aImg.src = e.target.result;};})(img);reader.readAsDataURL(file);}}

你可以从这里得到直播演示

单线解决方案:

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

<img id="blah" alt="your image" width="100" height="100" />
<input type="file"onchange="document.getElementById('blah').src = window.URL.createObjectURL(this.files[0])">

生成的URL将是:

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

有几种方法可以做到这一点。最有效的方法是在<输入>文件上使用URL.createObjectURL()。将此URL传递给img.src以告诉浏览器加载提供的图像。

这里有一个例子:

<input type="file" accept="image/*" onchange="loadFile(event)"><img id="output"/><script>var loadFile = function(event) {var output = document.getElementById('output');output.src = URL.createObjectURL(event.target.files[0]);output.onload = function() {URL.revokeObjectURL(output.src) // free memory}};</script>

您还可以使用FileReader.readAsDataURL()从您的<输入>中解析文件。这将在内存中创建一个包含图像Base64表示的字符串。

<input type="file" accept="image/*" onchange="loadFile(event)"><img id="output"/><script>var loadFile = function(event) {var reader = new FileReader();reader.onload = function(){var output = document.getElementById('output');output.src = reader.result;};reader.readAsDataURL(event.target.files[0]);};</script>

这个解决方案呢?

只需将数据属性“data-type=edable”添加到图像标签中,如下所示:

<img data-type="editable" id="companyLogo" src="http://www.coventrywebgraphicdesign.co.uk/wp-content/uploads/logo-here.jpg" height="300px" width="300px" />

你项目的剧本偏离了轨道…

function init() {$("img[data-type=editable]").each(function (i, e) {var _inputFile = $('<input/>').attr('type', 'file').attr('hidden', 'hidden').attr('onchange', 'readImage()').attr('data-image-placeholder', e.id);
$(e.parentElement).append(_inputFile);
$(e).on("click", _inputFile, triggerClick);});}
function triggerClick(e) {e.data.click();}
Element.prototype.readImage = function () {var _inputFile = this;if (_inputFile && _inputFile.files && _inputFile.files[0]) {var _fileReader = new FileReader();_fileReader.onload = function (e) {var _imagePlaceholder = _inputFile.attributes.getNamedItem("data-image-placeholder").value;var _img = $("#" + _imagePlaceholder);_img.attr("src", e.target.result);};_fileReader.readAsDataURL(_inputFile.files[0]);}};
//// IIFE - Immediately Invoked Function Expression// https://stackoverflow.com/questions/18307078/jquery-best-practises-in-case-of-document-ready(
function (yourcode) {"use strict";// The global jQuery object is passed as a parameteryourcode(window.jQuery, window, document);}(
function ($, window, document) {"use strict";// The $ is now locally scoped$(function () {// The DOM is ready!init();});
// The rest of your code goes here!}));

查看JSFiddle的演示

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

$(function () {$("input[name=file1]").previewimage({div: ".preview",imgwidth: 180,imgheight: 120});$("input[name=file2]").previewimage({div: ".preview2",imgwidth: 90,imgheight: 90});});
.preview > div {display: inline-block;text-align:center;}
.preview2 > div {display: inline-block;text-align:center;}
<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>Preview<div class="preview"></div>Preview2<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>

使用JavaScript(jQuery)和HTML5的多个图像示例

JavaScript(jQuery)

function readURL(input) {for(var i =0; i< input.files.length; i++){if (input.files[i]) {var reader = new FileReader();
reader.onload = function (e) {var img = $('<img id="dynamic">');img.attr('src', e.target.result);img.appendTo('#form1');}reader.readAsDataURL(input.files[i]);}}}
$("#imgUpload").change(function(){readURL(this);});}

标记(超文本标记语言)

<form id="form1" runat="server"><input type="file" id="imgUpload" multiple/></form>

这是一个多个文件版本,基于Ivan Baev的回答。

超文本标记语言

<input type="file" multiple id="gallery-photo-add"><div class="gallery"></div>

javascript/jQuery

$(function() {// Multiple images preview in browservar imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {var reader = new FileReader();
reader.onload = function(event) {$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);}
reader.readAsDataURL(input.files[i]);}}
};
$('#gallery-photo-add').on('change', function() {imagesPreview(this, 'div.gallery');});});

由于使用$. parseHTML,需要jQuery 1.8,这应该有助于XSS缓解。

这将开箱即用,您需要的唯一依赖项是jQuery。

以下是工作代码。

<input type='file' onchange="readURL(this);" /><img id="ShowImage" src="#" />

Javascript:

 function readURL(input) {if (input.files && input.files[0]) {var reader = new FileReader();
reader.onload = function (e) {$('#ShowImage').attr('src', e.target.result).width(150).height(200);};
reader.readAsDataURL(input.files[0]);}}

简单明了JS小提琴

当您希望事件从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>

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

function previewImage(fileObj, imgPreviewId) {var allowExtention = ".jpg,.bmp,.gif,.png";  //allowed to upload file typedocument.getElementById("hfAllowPicSuffix").value;var extention = fileObj.value.substring(fileObj.value.lastIndexOf(".") + 1).toLowerCase();var browserVersion = window.navigator.userAgent.toUpperCase();if (allowExtention.indexOf(extention) > -1) {if (fileObj.files) {if (window.FileReader) {var reader = new FileReader();reader.onload = function (e) {document.getElementById(imgPreviewId).setAttribute("src", e.target.result);};reader.readAsDataURL(fileObj.files[0]);} else if (browserVersion.indexOf("SAFARI") > -1) {alert("don't support  Safari6.0 below broswer");}} else if (browserVersion.indexOf("MSIE") > -1) {if (browserVersion.indexOf("MSIE 6") > -1) {//ie6document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);} else {//ie[7-9]fileObj.select();fileObj.blur();var newPreview = document.getElementById(imgPreviewId);
newPreview.style.border = "solid 1px #eeeeee";newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection.createRange().text + "')";newPreview.style.display = "block";
}} else if (browserVersion.indexOf("FIREFOX") > -1) {//firefoxvar firefoxVersion = parseFloat(browserVersion.toLowerCase().match(/firefox\/([\d.]+)/)[1]);if (firefoxVersion < 7) {//firefox7 belowdocument.getElementById(imgPreviewId).setAttribute("src", fileObj.files[0].getAsDataURL());} else {//firefox7.0+ document.getElementById(imgPreviewId).setAttribute("src", window.URL.createObjectURL(fileObj.files[0]));}} else {document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);}} else {alert("only support" + allowExtention + "suffix");fileObj.value = ""; //clear Selected fileif (browserVersion.indexOf("MSIE") > -1) {fileObj.select();document.selection.clear();}
}}function changeFile(elem) {//file object , preview img tag idpreviewImage(elem,'imagePreview')}
<input type="file"  id="netBarBig"  onchange="changeFile(this)"  /><img  src="" id="imagePreview" style="width:120px;height:80px;" alt=""/>

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();});

超文本标记语言

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

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

对于我的应用程序,使用加密的GET url参数,只有这个有效。我总是得到一个TypeError: $(...) is null。取自https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL

function previewFile() {var preview = document.querySelector('img');var file    = document.querySelector('input[type=file]').files[0];var reader  = new FileReader();
reader.addEventListener("load", function () {preview.src = reader.result;}, false);
if (file) {reader.readAsDataURL(file);}}
<input type="file" onchange="previewFile()"><br><img src="" height="200" alt="Image preview...">

对于多张图片上传(修改@IvanBaev的解决方案)

function readURL(input) {if (input.files && input.files[0]) {var i;for (i = 0; i < input.files.length; ++i) {var reader = new FileReader();reader.onload = function (e) {$('#form1').append('<img src="'+e.target.result+'">');}reader.readAsDataURL(input.files[i]);}}}

http://jsfiddle.net/LvsYc/12330/

希望这有助于某人。

试试这个

window.onload = function() {if (window.File && window.FileList && window.FileReader) {var filesInput = document.getElementById("uploadImage");filesInput.addEventListener("change", function(event) {var files = event.target.files;var output = document.getElementById("result");for (var i = 0; i < files.length; i++) {var file = files[i];if (!file.type.match('image'))continue;var picReader = new FileReader();picReader.addEventListener("load", function(event) {var picFile = event.target;var div = document.createElement("div");div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +"title='" + picFile.name + "'/>";output.insertBefore(div, null);});picReader.readAsDataURL(file);}
});}}
<input type="file" id="uploadImage" name="termek_file" class="file_input" multiple/><div id="result" class="uploadPreview">

默认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>

如果你正在使用React,这里有一个解决方案:

import * as React from 'react'import { useDropzone } from 'react-dropzone'
function imageDropper() {const [imageUrl, setImageUrl] = React.useState()const [imageFile, setImageFile] = React.useState()
const onDrop = React.useCallback(acceptedFiles => {const file = acceptedFiles[0]setImageFile(file)
// convert file to data: urlconst reader = new FileReader()reader.addEventListener('load', () => setImageUrl(String(reader.result)), false)reader.readAsDataURL(file)},[setImageFile, setImageUrl])const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop })
return (<div><div {...getRootProps()}>{imageFile ? imageFile.name : ''}{isDragActive ? <p>Drop files here...</p> : <p>Select image file...</p>}<input {...getInputProps()} /></div>{imageUrl && (<div>Your image: <img src={imageUrl} /></div>)}</div>)}

使用jQuery/javascript上传之前预览多个图像?

这将一次预览多个文件作为缩略图

Html

<input id="ImageMedias" multiple="multiple" name="ImageMedias" type="file"accept=".jfif,.jpg,.jpeg,.png,.gif" class="custom-file-input"  value=""><div id="divImageMediaPreview"></div>

脚本

$("#ImageMedias").change(function () {if (typeof (FileReader) != "undefined") {var dvPreview = $("#divImageMediaPreview");dvPreview.html("");$($(this)[0].files).each(function () {var file = $(this);var reader = new FileReader();reader.onload = function (e) {var img = $("<img />");img.attr("style", "width: 150px; height:100px; padding: 10px");img.attr("src", e.target.result);dvPreview.append(img);}reader.readAsDataURL(file[0]);});} else {alert("This browser does not support HTML5 FileReader.");}});

在CoDepen上的工作演示

jsfiddle上的工作演示

我希望这会有帮助。

在React中,如果文件在你的props中,你可以使用:

{props.value instanceof File && (<img src={URL.createObjectURL(props.value)}/>)}

这是最简单的方法


在从浏览器上传到服务器之前预览图像,而无需使用Ajax或任何复杂的函数。


它需要一个“关于变化”事件来加载图像。

function preview() {frame.src=URL.createObjectURL(event.target.files[0]);}
<form><input type="file" onchange="preview()"><img id="frame" src="" width="100px" height="100px"/></form>

预览多个图像点击这里

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

es2017方式

// convert file to a base64 urlconst readURL = file => {return new Promise((res, rej) => {const reader = new FileReader();reader.onload = e => res(e.target.result);reader.onerror = e => rej(e);reader.readAsDataURL(file);});};
// for democonst fileInput = document.createElement('input');fileInput.type = 'file';const img = document.createElement('img');img.attributeStyleMap.set('max-width', '320px');document.body.appendChild(fileInput);document.body.appendChild(img);
const preview = async event => {const file = event.target.files[0];const url = await readURL(file);img.src = url;};
fileInput.addEventListener('change', preview);

短双线

这是cmlevy答案的大小改进-尝试

<input type=file oninput="pic.src=window.URL.createObjectURL(this.files[0])"><img id="pic" />

<img id="blah" alt="your image" width="100" height="100" /><input type="file" name="photo" id="fileinput" /><script>$('#fileinput').change(function() {var url = window.URL.createObjectURL(this.files[0]);$('#blah').attr('src',url);});</script>

预览多个文件使用jQuery

$(document).ready(function(){$('#image').change(function(){$("#frames").html('');for (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[]" multiple /><br/><div id="frames"></div></body>

这是一个非常简单的方法,使用纯JavaScript上传前预览图像;

//profile_change is the id of the input field where we choose an imagedocument.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 willrepresent 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 selectedif(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 thenew 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 thefile 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")}});

这是超文本标记语言;

<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">