vlambda博客
学习文章列表

ajax图片上传插件

 <form action="" class="form" enctype="multipart/form-data">
 <input id="upfile" class="file" type="file" name="upfile" accept="image/png,image/jpg,image/jpeg">
 var upfile = $('#upfile').get(0).files[0]; //获取上传的文件;//get(0)将Jquery对象转换为DOM对象 if (upfile == ""||typeof(upfile) == "undefined") { alert('上传单据不能为空'); return false; }
 var formData = new FormData(); //创建一个formData formData.append('clinic', clinic); formData.append('clinic_id', clinic_id); formData.append('medical_service', medical_service); formData.append('medical_score', medical_score); formData.append('service_score', service_score); formData.append('work_score', work_score); formData.append('coast_score', coast_score); formData.append('reason', reason); formData.append('experience', experience); formData.append('money', money); formData.append('name', name); formData.append('upfile', upfile);



$.ajax({ method: 'post', data: formData, dataType: 'json', processData: false,//数据处理 contentType: false,//内容类型 cache: false, async: false, url: "/wp-admin/admin-ajax.php?action=feedback_posts", success: function (msg) { console.log(msg); // alert(msg.msg); // setTimeout(function (){ // location.reload(); // },2000) } });
});
/*上传图片到媒体库中*/function xset_attachment(){ $fujian = $_FILES['upfile']; $filename = $fujian['name']; $temp_arr = explode(".", $filename); $fileExt = array_pop($temp_arr); //附件保存格式【时间】 $upFileTime = date("YmdHis"); //更改上传文件的文件名为时间+随机数+后缀 $fujian['name'] = $upFileTime . "-" . uniqid() . "." . $fileExt; $uploaded_file = wp_handle_upload($fujian, array('test_form' => false));
// $content = str_replace($filename, $uploaded_file[url], $content); if (isset($uploaded_file['error'])) { echo "文件上传失败"; wp_die($uploaded_file['error']); } $file = $uploaded_file['file']; $new_file = iconv('GBK', 'UTF-8', $file); $url = iconv('GBK', 'UTF-8', $uploaded_file['url']); $type = $uploaded_file['type'];
$attachment = array( 'post_mime_type' => $type, 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit' );
$attach_id = wp_insert_attachment($attachment, $file, 0); require_once(ABSPATH . 'wp-admin/includes/image.php'); $attach_data = wp_generate_attachment_metadata($attach_id, $file); $res1 = wp_update_attachment_metadata($attach_id, $attach_data); return $attach_id;}
 $fid = xset_attachment();

$field_key11 = "upfile"; $value11 = $fid; update_field($field_key11, $value11, $post_id);