is it possible to preview local images before uploading them via a form?(是否可以在通过表单上传之前预览本地图像?)
问题描述
更具体地说,我想使用一个带有一个或多个用于图像的文件输入字段的表单.当这些字段发生更改时,我想在将数据发送到服务器之前显示相关图像的预览.
To be more specific, I want to use a form with one or more file input fields used for images. When those fields are changed, I'd like to show a preview of the associated image, before sending the data to the server.
我尝试了多种 javascript 方法,但总是遇到安全错误.我不介意使用 java 或 flash,只要解决方案对于那些没有它们的用户可以优雅地降级.(他们不会得到预览,也不会得到烦人的安装这个东西".)
I've tried a number of javascript approaches, but I always run into security errors. I wouldn't mind using java or flash, as long as the solution degraded gracefully for those users who didn't have them. (They wouldn't get previews, and they wouldn't get an annoying 'install this thing' either.)
有没有人以简单、可重复使用的方式做到这一点?
Has anyone done this in a simple, reusable way?
附:我知道有一个沙箱,但沙箱必须在一个黑暗、上锁的房间里,所有窗户都涂黑了吗?
P.S. I know there's a sandbox, but does the sandbox have to be in a dark, locked room with all the windows blacked out?
推荐答案
不需要花哨的东西.您所需要的只是 createObjectURL
函数,它创建一个可以用作图像 src
的 URL,并且可以直接来自本地文件.
No need for fancy stuff. All you need is the createObjectURL
function, which creates a URL that can be used as the image src
, and can come straight from a local file.
假设您使用文件输入元素 (<input type="file"/>
) 从用户的计算机中选择了几张图像.以下是为它创建图像文件预览的方法:
Let's say you selected a couple of images from the user's computer using a file input element (<input type="file" />
). Here's how you would create previews for image files for it:
function createObjectURL(object) {
return (window.URL) ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object);
}
function revokeObjectURL(url) {
return (window.URL) ? window.URL.revokeObjectURL(url) : window.webkitURL.revokeObjectURL(url);
}
function myUploadOnChangeFunction() {
if(this.files.length) {
for(var i in this.files) {
var src = createObjectURL(this.files[i]);
var image = new Image();
image.src = src;
// Do whatever you want with your image, it's just like any other image
// but it displays directly from the user machine, not the server!
}
}
}
这篇关于是否可以在通过表单上传之前预览本地图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以在通过表单上传之前预览本地图像?
基础教程推荐
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01