其中一個問題是文件上傳使用的機制不同於其他形式的<input>
類型。這就是爲什麼$this->input->post("userfile")
沒有爲你完成工作。其他答案建議使用javascript的FormData
,這也是。
HTML
一個非常簡單的形式選擇一個文件,並提交。請注意從簡單按鈕到<input type="submit"...
的更改。這樣做使JavaScript更容易使用FormData
對象。
FormData documentation
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://code.jquery.com/jquery-2.2.2.js"></script>
<title>Upload Test</title>
</head>
<body>
<?= form_open_multipart("upload/post", ['id' => 'uploader']); ?>
<input type="file" name="userfile">
<p>
<input type="submit" value="Upload">
</p>
<?php echo form_close() ?>
<div id="message"></div>
<script>
$('#uploader').submit(function (event) {
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
dataType: 'json',
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
console.log(data);
if (data.result === true) {
$("#message").html("<p>File Upload Succeeded</p>");
} else {
$("#message").html("<p>File Upload Failed!</p>");
}
$("#message").append(data.message);
}
});
});
</script>
</body>
</html>
JAVASCRIPT
使用FormData
捕捉領域。 請注意,不是處理按鈕點擊,我們處理提交事件。
$('#uploader').submit(function (event) {
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
dataType: 'json',
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
//uncomment the next line to log the returned data in the javascript console
// console.log(data);
if (data.result === true) {
$("#message").html("<p>File Upload Succeeded</p>");
} else {
$("#message").html("<p>File Upload Failed!</p>");
}
$("#message").append(data.message);
}
});
});
控制器
我已經添加了一些代碼,「報告」結果阿賈克斯,並會顯示它上傳頁面上。
class Upload extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(['form', 'url']);
}
public function index()
{
$this->load->view('upload_v');
}
public function post()
{
$this->load->library("upload");
$this->upload->initialize(array(
"upload_path" => './uploads/',
'allowed_types' => 'gif|jpg|png|doc|txt',
"overwrite" => FALSE,
"max_filename" => 300,
"encrypt_name" => TRUE,
));
$successful = $this->upload->do_upload('userfile');
if($successful)
{
$data = $this->upload->data();
$image_file = $data['file_name'];
$msg = "<p>File: {$image_file}</p>";
$this->data_models->update($this->data->INFO, array("image" => $image_file));
} else {
$msg = $this->upload->display_errors();
}
echo json_encode(['result' => $successful, 'message' => $msg]);
}
}
這將上傳您的文件。您的工作可能沒有完成,因爲我懷疑您沒有將所需的所有文件信息保存到數據庫。那,我懷疑你會被上傳文件的名字感到驚訝。
我建議你研究一下PHP handles file uploads以及如何檢查文件上傳到SO上的一些類似codeigniter相關的問題。
你是不是傳遞文件上傳類即'$ file'。初始化後,你應該有'if(!$ this-> upload-> do_upload('userfile')){/ * code * /}'。檢查上傳的基本示例[這裏](https://www.codeigniter.com/userguide3/libraries/file_uploading.html#the-controller)。 – Tpojka
我已經試過但沒有工作。 – Mehur
什麼是錯誤? 'var_dump('$ this-> input-> post('userfile'); exit;'檢查PHP是否獲得這些數據。 – Tpojka