我想通过以下表单上传图片:
<?php echo form_open_multipart('posts/create'); ?>
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" name="title" placeholder="Add Title" required>
</div>
<div class="form-group">
<label>Body</label>
<textarea id="editor1" class="form-control" name="body" placeholder="Add Body" required></textarea>
</div>
<div class="form-group">
<label>Category</label>
<select name="category_id" class="form-control">
<?php foreach($categories as $category): ?>
<option value="<?php echo $category['id']; ?>"><?php echo $category['name']; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label>Upload Image</label>
<input type="file" name="userfile" size="20">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
当我发送信息时,我会检查POST请求是否具有正确的数据。不是。
它告诉我所有输入都希望文件输入...
这是控制器,称为Posts,而函数称为create。
public function create() {
$data['title'] = 'Create post';
$data['categories'] = $this->post_model->get_categories();
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('body', 'Body', 'required');
if (!$this->form_validation->run()) {
$this->load->view('templates/header');
$this->load->view('posts/create', $data);
$this->load->view('templates/footer');
} else {
// Upload image
$config['upload_path'] = 'assets/images/posts';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['max_width'] = 2000;
$config['max_height'] = 2000;
$this->load->library('upload', $config);
# Here's where I print the request.
print_r($_POST);
if (!$this->upload->do_upload('userfile')) {
$errors = array('error' => $this->upload->display_errors());
$post_image = 'noimage.jpg';
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
echo $post_image;
/* $this->post_model->create_post($post_image);
redirect('posts'); */
}
}
autoloader.php配置正确...
$autoload['helper'] = array('url', 'form', 'text');
如果有人需要整个项目,请here you go
我正在使用Docker运行它,您可以使用docker-compose up --build
对其进行测试。
答案 0 :(得分:1)
我已经测试了您的代码,并且工作正常,这是var_dump($_FILES);
的结果:
["userfile"]=>
array(5) {
["name"]=>
string(9) "image.jpg"
["type"]=>
string(10) "image/jpeg"
["tmp_name"]=>
string(23) "C:\xampp\tmp\phpB54.tmp"
["error"]=>
int(0)
["size"]=>
int(493443)
}
没问题。
但请记住,您应该给$config['upload_path']
一个相对路径或一个绝对路径,因此您可以考虑使用此$config['upload_path'] = './assets/images/posts';
或最好使用$config['upload_path'] = FCPATH'assets/images/posts';
< / p>
答案 1 :(得分:0)
编辑控制器Posts.php并添加:
SessionPool
是解决方案。