Dav*_*vid 5 javascript jquery html5
我试图从html 文件输入中删除值.
<input type="file" name="images" id="i1" class="imageup" multiple />
Run Code Online (Sandbox Code Playgroud)
我似乎无法访问.files数组来删除其中一个值.我曾尝试使用隐藏的输入类型与文件值,但我不认为这可以做....所以我试图访问输入元素删除!
所有代码都有一个小提琴.有很多东西可以复制情况,但控制删除事件的代码大约是js的一半.
http://jsfiddle.net/dheffernan/ryrfS/1
有没有人有一个访问方法,例如多个文件上传和删除的第三个输入值?
下面的js代码 - 使用.splice尝试.
var files=jQuery('#i'+inputid)[0].files;
for (var i = 0; i < files.length; i++) {
console.log(files[i].name);
}
var inputname= 3;
jQuery('#i'+inputid).splice(inputname, 1);
// no files are being deleted!!!
console.log('2nd test');
var files=jQuery('#i'+inputid)[0].files;
for (var i = 0; i < files.length; i++) {
console.log(files[i].name);
}
}
Run Code Online (Sandbox Code Playgroud)
使用html5 FormData解决方案:
基本上将图像添加到 FormData,使用 ajax 提交它并返回我上传它们的网址(我包括了用于 wordpress 的 php)。我从 js 代码和 php 代码中删除了所有数据验证以保持简短+我仍然需要针对 ie9/旧版本浏览器的解决方法。
jQuery 代码:
jQuery(document).on('change', '.imageup', function(){
var id= jQuery(this).attr('id');
var length= this.files.length;
if(length>1) {// if a multiple file upload
var images = new FormData();
images.append('action', 'uploadimg'); //wordpress specific add functionname
jQuery.each(event.target.files, function(key, value ){
images.append(key, value);
});
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
type: 'POST',
data: images,
cache: false,
processData: false,
contentType: false,
success: function(data) {
var obj= JSON.parse(data);
jQuery.each(obj,function(key, value){
if(key!='errors') {
var ind = value.lastIndexOf("/") + 1;
var filename = value.substr(ind);
//do something here with filename
console.log(filename);
}
});
}//end of success function
}); //end ajax
}
});
Run Code Online (Sandbox Code Playgroud)
php代码wordpress,如果不使用wordpress更改上面的url等。
function uploadimg() {
$error = false;
$files = array();
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$upload_overrides = array( 'test_form' => false );
$url=array();
foreach($_FILES as $file){
$uploadimage= $file;
$movefile = wp_handle_upload( $uploadimage, $upload_overrides );
if ( $movefile ) {
if($movefile['url']) {
$url[]=$movefile['url'];
} else {
$url['errors'][]="error ".$movefile['file']." is not valid";
}
} else {
}
}
$url['errors'][]="error is not valid";
echo json_encode($url);
exit;
}
add_action('wp_ajax_uploadimg', 'uploadimg');
add_action('wp_ajax_nopriv_uploadimg', 'uploadimg');
Run Code Online (Sandbox Code Playgroud)