[英]Uploading a file in CodeIgniter PHP Using Ajax And jQuery
[英]uploading csv file using jquery ajax and codeigniter
在這里,我想使用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.");
}
});
});
閱讀文件上傳類 (尤其是在“控制器”部分),以了解如何在服務器端處理文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.