Ajax 上传不起作用 [英] Ajax upload not working codeigniter
问题描述
我正在使用 codeigniter 3.1 .我想使用ajax发布上传数据.
I am using codeigniter 3.1 . I want to post upload data using ajax.
Ajax 上传文件不起作用.但是当我发布没有 ajax 的简单表单时,它工作正常.
Ajax upload file not working. But when i post the simple form without ajax, it working fine.
我不知道为什么,但控制台没有错误.
I don't know why but no error in console.
HTML
<?php echo form_open_multipart(site_url("upload/post"), ['id' => 'uploader']) ?>
<input type="file" name="userfile" value="">
<input type="submit" value="Submit" />
<?php echo form_close() ?>
JAVASCRIPT
$('#uploader').submit(function (event) {
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
dataType: 'json',
data: new FormData(this)
});
});
控制器
public function post()
{
$this->load->helper('url');
$this->load->helper('form');
$this->load->library("upload");
$file = $this->common->nohtml($this->input->post("userfile"));
$this->upload->initialize(array(
"upload_path" => 'upload',
"overwrite" => FALSE,
"max_filename" => 300,
"encrypt_name" => TRUE
));
$this->upload->do_upload('userfile');
$data = $this->upload->data();
$image_file = $data['file_name'];
}
推荐答案
其中一个问题是文件上传使用的机制与其他表单 类型不同.这就是为什么
$this->input->post("userfile")
没有为您完成工作的原因.其他答案建议使用 javascript 的 FormData
,这个也可以.
One of the issues is that file uploading uses a different mechanism than the other form <input>
types. That is why $this->input->post("userfile")
isn't getting the job done for you. Other answers have suggested using javascript's FormData
and this one does too.
HTML
用于选择文件并提交的非常简单的表单.请注意从简单按钮到 的更改.这样做可以让 javascript 更容易使用
FormData
对象.
A very simple form for picking a file and submitting it. Note the change from a simple button to <input type="submit"...
. Doing so makes it a lot easier for the javascript to use the FormData
object.
<!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
来捕获字段.请注意,我们处理提交事件而不是处理按钮点击.
Use FormData
to capture the fields.
Note that instead of handling the button click we handle the submit event.
$('#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);
}
});
});
控制器
我添加了一些代码,将结果报告"到 ajax 并将其显示在上传页面上.
I've added some code that "reports" results to ajax and will display it on the upload page.
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]);
}
}
这将上传您的文件.您的工作可能尚未完成,因为我怀疑您没有将所需的所有文件信息保存到数据库中.那,我怀疑您会对上传的文件的名称感到惊讶.
This will upload your file. Your work probably isn't done because I suspect that your are not saving all the file info you need to the db. That, and I suspect you are going to be surprised by the name of the uploaded file.
我建议你研究一下 PHP 如何处理文件上传和在 SO 上检查有关文件上传的一些类似 codeigniter 相关问题.
I suggest you study up on how PHP handles file uploads and examine some of the similar codeigniter related questions on file uploads here on SO.
这篇关于Ajax 上传不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!