当他们选择一个同名的文件时,不会触发Javascript文件输入onchange [英] Javascript file input onchange isn't triggered when they select a file with the same name

查看:96
本文介绍了当他们选择一个同名的文件时,不会触发Javascript文件输入onchange的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的网页上有一个文件输入,允许用户上传图片。



我设置了一些东西,当他们选择一个图片时,的文件输入被触发,并显示他们的图像预览。

有时一旦他们看到预览,他们想调整图像在本地(比如使用绘画裁剪)。然后他们点击保存在绘图中,然后单击文件输入并再次选择文件。

问题是,当他们再次选择文件时,输入的更改事件isn即使图像数据已经改变,也不会触发,如果他们尝试上传文件到我的服务器,旧的图像数据被使用。

有什么办法来检测什么时候用户实际上选择了一个文件,而不是当文件输入变化事件发生时,以便我可以很好地处理的情况下?编辑:请注意,我可以删除和重新创建一个文件输入每次用户选择一个图像,这个工程,但这意味着文件输入说'没有选择的文件'这使用户混淆。

解决方案

一个简单的解决方案是执行以下操作:

  this.input.addEventListener('click', function(){
this.value ='';
},false);

这会导致在用户选择文件时触发更改事件,因为初始点击打开文件浏览弹出菜单清除输入。


I have a file input in my webpage that allows a user to upload images.

I have things set up so that when they select an image, the change event of the file input is triggered and is shows them a preview of their image.

Sometimes once they see the preview they want to tweak the image a bit locally (eg using paint to crop it). They then click save in paint and click the file input and select the file again.

The problem is that when they select the file again, the change event of the input isn't triggered even though the image data has changed and if they try to upload the file to my server the old image data is used.

Is there any way to detect when the user actually selects a file, rather than when the file input change event occurs so that I can nicely deal with the case?

EDIT: Note that I can just delete and recreate a file input each time a user selects an image and this works but it means that the file input says 'no file chosen' which confuses the user.

解决方案

A simple solution is to do the following:

this.input.addEventListener('click', function() {
    this.value = '';
}, false);

This causes the change event to be triggered any time the user selects a file, because the initial click that opens the file browsing popup clears the input.

这篇关于当他们选择一个同名的文件时,不会触发Javascript文件输入onchange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆