javascript - jQuery拖放+点击图片上传
问题描述
我想要一个简单的拖放区来通过 AJAX 和 jQuery 上传图像。我找到了一些插件,但它们对于需要的东西来说太定制了,我无法让它们中的任何一个正常工作。 我还希望放置区是可点击的,以便从操作系统文件对话框中手动选择一个文件。
我找到了这个脚本,它工作正常,但放置区域不可点击:
// ---------------------------- drop zone to upload image : '#dropfile'
$(document).on('dragenter', '#dropfile', function() {
return false;
});
$(document).on('dragover', '#dropfile', function(e){
e.preventDefault();
e.stopPropagation();
return false;
});
$(document).on('dragleave', '#dropfile', function(e) {
e.preventDefault();
e.stopPropagation();
return false;
});
$(document).on('drop', '#dropfile', function(e) {
if(e.originalEvent.dataTransfer){
if(e.originalEvent.dataTransfer.files.length) {
// Stop the propagation of the event
e.preventDefault();
e.stopPropagation();
// Main function to upload
upload(e.originalEvent.dataTransfer.files);
}
}
return false;
});
function upload(files) {
var f = files[0] ;
// Only process image files.
if (!f.type.match('image/jpeg')) {
alert(‘The file must be a jpeg image’) ;
return false ;
}
var reader = new FileReader();
// When the image is loaded, run handleReaderLoad function
reader.onload = handleReaderLoad;
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
function handleReaderLoad(evt) {
var pic = {};
pic.file = evt.target.result.split(',')[1];
var str = jQuery.param(pic);
$.ajax({
type: 'POST',
url: ‘url_to_php_script.php’,
data: str,
success: function(data) {
//do_something(data) ;
}
});
}
所以我添加了一个不可见的文件类型输入,但是图像数据似乎被发送了两次。我想这是由于原始放置区的不良事件传播:
// ---------------------------- clickable drop zone with invisible file input '#inputFile'
$('#dropfile).on('click', function() {
$('input#inputFile').trigger('click');
$('input#inputFile').change(function(e) {
upload($('input#inputFile')[0].files);
});
});
我尝试添加这些行,但数据总是发送两次:
$('#dropfile).on('click', function() {
$('input#inputFile').trigger('click');
$('input#inputFile').change(function(e) {
upload($('input#inputFile')[0].files);
// -------------- stop sending data twice ???
e.preventDefault();
e.stopPropagation();
return false;
});
});
解决方案
我仍然不知道为什么数据被发送两次,但我在这里找到了一个更好的脚本: https ://makitweb.com/drag-and-drop-file-upload-with-jquery-and-ajax/
推荐阅读
- javascript - 使用谨慎的元素在 Javascript 中将树构建为矩阵
- mysql - mysqldump返回权限被拒绝的问题
- javascript - 确定本地日期时间是否在日期时间窗口内
- url - 自动将 URL 替换为标题 Google Docs
- algorithm - 使用给定规则将 x,y 从 1,1 更改为 p,q
- java - 如何使用 JSON-B 反序列化未知属性?
- paypal - 设置交易与设置授权
- office-ui-fabric - 将 FluentUI Stack 组件制成的拆分窗格中的宽度固定为 50/50
- wordpress - 显示特定类别标签中的帖子数量
- django - Django RSS 提要:有什么方法可以缓存 M2M 关系以显示在 item_title 中?