我正在异步上传图像,为此我得到了这个很好的教程。我阅读了所有内容并尝试删除我不需要的模型并根据我的需要制作它,但是当我运行它时我没有收到错误并且文件也没有上传。
我在控制器上传功能中放了一个回声,但我也没有得到回声字符串,即使我将完整路径放在 ajaxfileupload URL中。
这是我的看法:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="<?php echo site_url()?>public/assets/js/ajaxfileupload.js"></script>
<script>
$(function() {
$('#upload_file').submit(function(e) {
e.preventDefault();
$.ajaxFileUpload({
url : 'upload2/upload_file',
secureuri : false,
fileElementId: 'userfile',
dataType : 'json',
data : {
'title': $('#title').val()
},
success : function (data, status)
{
if(data.status != 'error')
{
$('#files').html('<p>Reloading files...</p>');
refresh_files();
$('#title').val('');
}
alert(data.msg);
}
});
return false;
});
});
</script>
</head>
<body>
<h1>Upload File</h1>
<form method="post" action="" id="upload_file">
<label for="title">Title</label>
<input type="text" name="title" id="title" value="" />
<label for="userfile">File</label>
<input type="file" name="userfile" id="userfile" size="20" />
<input type="submit" name="submit" id="submit" />
</form>
<h2>Files</h2>
<div id="files"></div>
</body>
</html>
我的控制器是这样的:
<?php
class Upload2 extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('url');
}
public function index()
{
$this->load->view('upload');
}
public function upload_file()
{
/* It's not even showing me this echo and the path is
OK too, and even I put the whole path but no result. */
echo "in upload_file";
$status = "";
$msg = "";
$file_element_name = 'userfile';
if (empty($_POST['title']))
{
$status = "error";
$msg = "Please enter a title";
}
if ($status != "error")
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|doc|txt';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name))
{
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else
{
$data = $this->upload->data();
$file_id = $this->files_model->insert_file($data['file_name'], $_POST['title']);
if($file_id)
{
$status = "success";
$msg = "File successfully uploaded";
}
else
{
unlink($data['full_path']);
$status = "error";
$msg = "Something went wrong when saving the file, please try again.";
}
}
@unlink($_FILES[$file_element_name]);
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}
}
?>