我希望能够在上传文件(图像)之前预览它。预览操作应该在浏览器中全部执行,而不使用Ajax上传图像。
我该怎么做?
我希望能够在上传文件(图像)之前预览它。预览操作应该在浏览器中全部执行,而不使用Ajax上传图像。
我该怎么做?
当前回答
这个解决方案怎么样?
只需将数据属性“data type=editable”添加到图像标记中,如下所示:
<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 parameter
yourcode(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演示
其他回答
这是一个基于Ivan Baev答案的多文件版本。
HTML
<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>
JavaScript/jQuery
$(function() {
// Multiple images preview in browser
var 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。
如果您使用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: url
const 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>
)
}
imgInp.oncange=evt=>{const[file]=imgInp.fileif(文件){blah.src=URL.createObjectURL(文件)}}<form runat=“server”><input accept=“image/*”type='file'id=“imgInp”/><img id=“blah”src=“#”alt=“your image”/></form>
对于我的应用程序,使用加密的GET url参数,只有这一点有效。我总是得到一个TypeError:$(…)为空。摘自https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
函数previewFile(){var preview=document.querySelector('img');var file=document.querySelector('input[type=file]').files[0];var reader=新文件读取器();reader.addEventListener(“load”,函数(){preview.src=读取结果;},假);if(文件){reader.readAsDataURL(文件);}}<input-type=“file”onchange=“previewFile()”><br><img src=“”height=“200”alt=“图像预览…”>
有几种方法可以做到这一点。最有效的方法是在<input>的文件上使用URL.createObjectURL()。将此URL传递给img.src,告诉浏览器加载提供的图像。
下面是一个示例:
<input-type=“file”accept=“image/*”onchange=“loadFile(event)”><img id=“output”/><脚本>var loadFile=函数(事件){var output=document.getElementById('output');output.src=URL.createObjectURL(event.target.files[0]);output.onload=函数(){URL.revokeObjectURL(output.src)//释放内存}};</script>
您还可以使用FileReader.readAsDataURL()从<input>解析文件。这将在内存中创建一个字符串,其中包含图像的base64表示。
<input-type=“file”accept=“image/*”onchange=“loadFile(event)”><img id=“output”/><脚本>var loadFile=函数(事件){var reader=新文件读取器();reader.onload=函数(){var output=document.getElementById('output');output.src=读取结果;};reader.readAsDataURL(event.target.files[0]);};</script>