我正在尝试使用ajax和codeigniter php后端将图像上传到服务器,文件选择正常工作
FileList {0: File, length: 1}
File {name: "21430081_1852077344807727_5107330097727092003_n.jpg", lastModified: 1504942183875, lastModifiedDate: Sat Sep 09 2017 14:29:43 GMT+0700 (WIB), webkitRelativePath: "", size: 25179, …}
文件是“非空”但是当我通过ajax将此文件列表发送到我的控制器时,结果
{datas: "NULL"}
datas : "NULL"
控制器必须在服务器(http://localhost/upload_folder/file.jpg)
中返回图片网址我的控制器代码
class Ajax extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper(array('form', 'url', 'file'));
$this->load->library(array('upload','user_agent'));
//error_reporting(E_ALL | E_STRICT);
}
public function post_image()
{
$this->upload->initialize(array(
"allowed_types" => "jpg|png|jpeg",
"upload_path" => "./uploads/",
));
$image = $this->input->post('image');
if($this->upload->do_upload($image))
// if(is_object($image))
{
$data = $this->upload->get_upload_data();
echo json_encode(['datas' => base_url().$data[0]['file_name']]);
}else
{
echo json_encode(['datas' => "error"]);
}
}
}
我的ajax代码
function saveToServer(file) {
var fd = new FormData();
fd.append('image', file);
//console.log(fd.get('image'));
$.ajax({
url : "<?php echo base_url(); ?>admin/Ajax/post_image",
type : "POST",
data : {'image' : fd},
processData: false,
contentType : false,
success : function(datas) {
// do something
const url = JSON.parse(datas).data;
insertToEditor(url);
}
});
}
我正在使用此代码检索图像文件
function selectLocalImage() {
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('name', 'image-input')
input.click();
// Listen upload local image and save to server
input.onchange = () => {
const file = input.files;
// file type is only image.
//if (/^jpg\//.test(file.type)) {
saveToServer(file);
console.log(file);
//} else {
// console.warn('You could only upload images.');
//}
};
}
答案 0 :(得分:0)
这是我对上述问题的“修复”。
当我检查$_POST
或$image = $this->input->post('image');
时它总是为NULL,但是当我检查$_FILES
时,它会返回我在视图中发布的文件,因此我将整个函数更改为(几乎)为native PHP上传文件
if ($_FILES['image'] !== null){
//$image = $this->input->post($_FILES['image']['name']);
//$this->upload->do_multi_upload($image);
$target_dir = "./uploads/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(move_uploaded_file($_FILES["image"]["tmp_name"], $target_file))
{
$data = $this->upload->get_multi_upload_data();
echo json_encode(['data' => 'uploads/'.$_FILES["image"]["name"]]);
}else
{
//echo json_encode(['datas' => gettype($image)]);
echo json_encode("not uploaded!");
}
}else
{
echo json_encode("nothing!");
}
它不是最佳解决方案,但我已解决了我的问题(暂时)。