我有一个多图片上传表单,以下代码适用于上传。我需要将文件名保存到数据库到数据库,但我无法弄清楚如何正确地做到这一点。
uploadform.php
:
echo form_open_multipart('gallery/upload');
<input type="file" name="photo" size="50" />
<input type="file" name="thumb" size="50" />
<input type="submit" value="Upload" />
</form>
gallery_model.php
function multiple_upload($upload_dir = 'uploads/', $config = array())
{
/* Upload */
$CI =& get_instance();
$files = array();
if(empty($config))
{
$config['upload_path'] = realpath($upload_dir);
$config['allowed_types'] = 'gif|jpg|jpeg|jpe|png';
$config['max_size'] = '2048';
}
$CI->load->library('upload', $config);
$errors = FALSE;
foreach($_FILES as $key => $value)
{
if( ! empty($value['name']))
{
if( ! $CI->upload->do_upload($key))
{
$data['upload_message'] = $CI->upload->display_errors(ERR_OPEN, ERR_CLOSE); // ERR_OPEN and ERR_CLOSE are error delimiters defined in a config file
$CI->load->vars($data);
$errors = TRUE;
}
else
{
// Build a file array from all uploaded files
$files[] = $CI->upload->data();
}
}
}
// There was errors, we have to delete the uploaded files
if($errors)
{
foreach($files as $key => $file)
{
@unlink($file['full_path']);
}
}
elseif(empty($files) AND empty($data['upload_message']))
{
$CI->lang->load('upload');
$data['upload_message'] = ERR_OPEN.$CI->lang->line('upload_no_file_selected').ERR_CLOSE;
$CI->load->vars($data);
}
else
{
return $files;
}
/* -------------------------------
Insert to database */
// problem is here, i need file names to add db.
// if there is already same names file at the folder, it rename file itself. so in such case, I need renamed file name :/
}
}
答案 0 :(得分:1)
您应该仅为数据库操作保留模型。所有上传处理和文件移动都必须在控制器中完成。模型必须在数据库中插入关于照片的记录,并且就此而言。
作为对您问题的回复,请执行print_r($files)
并查看其中包含的内容。它应该有原始文件名。它可能就像上面所说的artmania:$files[0]['file_name']
。你应该能够使用这样的foreach结构遍历你的$ files数组:
foreach($files as $file) {
$file_name = $file['file_name'];
}
您可以以相同的方式获取有关该文件的所有其他数据。 CodeIgniter手册说明了$this->upload->data()
:
这是一个返回的辅助函数 包含所有数据的数组 与您上传的文件有关。这里 是数组原型:
Array
(
[file_name] => mypic.jpg
[file_type] => image/jpeg
[file_path] => /path/to/your/upload/
[full_path] => /path/to/your/upload/jpg.jpg
[raw_name] => mypic
[orig_name] => mypic.jpg
[file_ext] => .jpg
[file_size] => 22.2
[is_image] => 1
[image_width] => 800
[image_height] => 600
[image_type] => jpeg
[image_size_str] => width="800" height="200"
)
更多信息check out the manual。