这里我想使用 jquery ajax 函数上传和移动 csv 文件。
$("#file").change(function() {
alert($("#file").val());
$.ajax({
url: "<?php echo base_url(); ?>index.php/Task_controller/upload_tasksquestion",
type: "post",
dataType: 'json',
processData: false,
contentType: false,
data: {file: $("#file").val()},
success: function(text) {
alert(text);
if(text == "success") {
alert("Your image was uploaded successfully");
}
},
error: function() {
alert("An error occured, please try again.");
}
});
});
我的html代码是:
< input type="file" class="form-control" id="file" name="file">
我正在控制器功能中测试上传的文件名 就像 $this->input->post('file');
但它没有到达控制器,我想将该文件移动到文件夹中。 请帮我解决我做错的地方...
我的服务器端代码是:
$curdate=date('Y-m-d');
$path='./assets/fileuploads/';
$file=basename($_FILES['file']['name']);
list($txt, $ext) = explode(".", $file);
$actual_file_name = time().substr($txt, 5).".".$ext;
if(move_uploaded_file($_FILES['file']['tmp_name'],$path.$actual_file_name))
您需要使用 FormData 通过 AJAX 发送文件。
将文件存储在 FormData 对象中,并将该对象作为您的
data
传递。
$("#file").change(function() {
var fd = new FormData();
fd.append('file', this.files[0]); // since this is your file input
$.ajax({
url: "<?php echo base_url(); ?>index.php/Task_controller/upload_tasksquestion",
type: "post",
dataType: 'json',
processData: false, // important
contentType: false, // important
data: fd,
success: function(text) {
alert(text);
if(text == "success") {
alert("Your image was uploaded successfully");
}
},
error: function() {
alert("An error occured, please try again.");
}
});
});
阅读文件上传类(尤其是控制器部分)了解如何在服务器端处理文件。
jQuery(document).ready(function($) {
$('.import-btn').on('click', function() {
$('#fileImport').click();
})
$('#fileImport').on('change', function() {
var fileData = new FormData();
var file = this.files[0];
if (file) {
fileData.append("file", file);
}
fileData.append("action", "import_data");
$.ajax({
url: "<?php echo admin_url("admin-ajax.php"); ?>",
type: "POST",
data: fileData,
processData: false,
contentType: false,
success: function(response) {
if (response.success) {
Swal.fire({
title: "Success",
text: response.data.message,
icon: "success"
});
} else {
Swal.fire({
title: "Error",
text: response.data.message,
icon: "error"
});
}
},
error: function(xhr, status, error) {
alert(error);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
add_action('wp_ajax_nopriv_import_data', 'import_data');
add_action('wp_ajax_import_data', 'import_data');
function import_data()
{
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (!empty($_FILES['file']) && isset($_FILES['file']['name'])) {
$fileTmpName = $_FILES['file']['tmp_name'];
if (($handle = fopen($fileTmpName, "r")) !== FALSE) {
$header = fgetcsv($handle);
while (($data = fgetcsv($handle)) !== FALSE) {
$post_title = isset($data[1]) ? $data[1] : '';
$category = isset($data[4]) ? $data[4] : '';
$post_content = isset($data[5]) ? wp_strip_all_tags(trim($data[5])) : '';
$post_thumbnail_url = isset($data[6]) ? $data[6] : '';
$args = array(
'post_type' => 'news',
'post_title' => $post_title,
'post_content' => $post_content,
'post_status' => 'publish'
);
$post_id = wp_insert_post($args);
if (!$post_id) {
wp_send_json_error(array("message" => "Error while importing post"));
} else {
update_post_meta($post_id, 'category', $category);
$upload_dir = wp_upload_dir();
$image_name = basename($post_thumbnail_url);
$type = wp_check_filetype($post_thumbnail_url)['type'];
$upload_path = $upload_dir['path'] . '/' . $image_name;
$image_url = $upload_dir['url'] . '/' . $image_name;
$image_data = file_get_contents($post_thumbnail_url);
if (file_put_contents($upload_path, $image_data)) {
$args = array(
'guid' => $image_url,
'post_status' => 'inherit',
'post_parent' => $post_id,
'post_mime_type' => $type,
'post_title' => $image_name
);
$attachment_id = wp_insert_attachment($args, $upload_path, $post_id);
if ($attachment_id) {
$attachment_metadata = wp_generate_attachment_metadata($attachment_id, $upload_path);
wp_update_attachment_metadata($attachment_id, $attachment_metadata);
set_post_thumbnail($post_id, $attachment_id);
} else {
wp_send_json_error(array("message" => "Error"));
wp_die();
}
}
}
}
fclose($handle);
wp_send_json_success(array("message" => "Imported Successfully"));
}
}
} else {
wp_send_json_error(array("message" => "Error"));
wp_die();
}
}