[已解决]
我的控制器功能出现问题。我想上传一张图片两次,并将其保存在同一目录中,但是文件名不同。
这是我的表格(view.php):
<form action="<?php echo base_url("process/testFunction"); ?>" enctype="multipart/form-data" method="post">
<input type="file" name="file_data" size="50" required>
<input type="hidden" name="user_id" value="<?php echo $this->session->userdata('user_id'); ?>" readonly>
<input type="hidden" name="purpose" value="Picture" readonly>
<input type="submit" value="Save Changes">
</form>
controller.php:
function testFunction(){
$userID = $this->input->post('user_id');
$purpose = $this->input->post('purpose');
$randomText = time();
if($purpose == "Picture"){
$uploadPath = "./uploads/images/";
$allowedTypes = "jpg|jpeg|png";
$maxSize = 10000000;
$fileName = "PP_".$userID.".jpeg";
$fileName2 = "PP_".$userID."_".$randomText.".jpeg"; //for backup
}
$config = array(
'upload_path' => $uploadPath,
'allowed_types' => $allowedTypes,
'max_size' => $maxSize,
'file_name' => $fileName
);
$configClone = array(
'upload_path' => $uploadPath,
'allowed_types' => $allowedTypes,
'max_size' => $maxSize,
'file_name' => $fileName2
);
$this->load->library('upload', $config);
$this->load->library('upload', $configClone);
if($this->upload->do_upload('file_data')){
echo "Uploaded";
}else{
echo $this->upload->display_errors();
}
}
我的代码中当前正在发生的是。虽然它会上传2张相同的图片。具有“随机文本”的文件名不起作用。
[Solution]:控制器文件。我修改了几行。
参考:下面是哈维尔的答案
$this->load->library('upload', $config);
if($this->upload->do_upload('file_data')){
unset($this->upload);
$this->load->library('upload', $configClone);
$this->upload->do_upload('file_data');
echo "Uploaded";
}else{
echo $this->upload->display_errors();
}
即使使用不同的配置数组,连续两次加载上载库也不会执行任何操作。如果库已在内存中,则Codeigniter将忽略第二个$this->load->library();
语句。目的是防止冲突,比赛条件等。
您需要:-
例如,在处理第一次上载后,可以使用unset($this->upload);
来达到第3点。
删除此行
$this->load->library('upload', $configClone);
更改
if($this->upload->do_upload('file_data')){
$this->upload->initialize($configClone);
if($this->upload->do_upload('file_data')){
echo "Uploaded";
}else{
echo $this->upload->display_errors();
}
}else{
echo $this->upload->display_errors();
}