我希望能够在上传文件(图像)之前预览它。预览操作应该在浏览器中全部执行,而不使用Ajax上传图像。
我该怎么做?
我希望能够在上传文件(图像)之前预览它。预览操作应该在浏览器中全部执行,而不使用Ajax上传图像。
我该怎么做?
当前回答
如果您使用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>
)
}
其他回答
这个解决方案怎么样?
只需将数据属性“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演示
创建一个加载文件并触发自定义事件的函数怎么样。然后将侦听器附加到输入。这样,我们可以更灵活地使用文件,而不仅仅是预览图像。
/**
* @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 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。
我已经制作了一个插件,由于互联网,它可以在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>
这里有一种在上传前使用纯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">