我构建上传zip文件的功能,但是当用户上传文件两次时,它没有删除第一个上传的文件,但是在文件名中添加了增量编号((file.zip,file1.zip,file2.zip ,,,等)
所以我想告诉用户上传相同文件名时的功能删除第一个文件并上传第二个文件或替换它...任何人都帮我怎么做......
/**
* change book source file
*
* @param integer $book_id
*/
public function upload_book_zip($book_id) {
$vars = array();
$vars['upload_path'] = PUBPATH . 'global/modules/bookstore/files/books_source_file/';
$vars['allowed_types'] = 'zip';
$vars['max_size'] = '30720';
$vars['book_id'] = $book_id;
$book = $this->d_book->find_by_id($book_id);
if (isset($_POST['submit'])) {
$file_name = $this->upload($vars);
if ($file_name === NULL) { // error happens while uploading file
$vars['upload_errors'] = $this->upload->display_errors("<p class='notification n-error'>", "</p>");
} else {
$this->d_book->update_one_field($book_id, 'bo_path_zip', $file_name);
$this->session->set_flashdata('success_msg', lang('file_uploaded'));
redirect('bookstore/admin_d_book/');
}
} else {
$vars['upload_errors'] = NULL;
}
if ($book->bo_path_zip) { // load cover image
$vars['file_path'] = base_url() . 'global/modules/bookstore/files/books_source_file/' . $book->bo_path_zip;
} else {
$vars['file_path'] = NULL;
}
$vars['controller_name'] = 'admin_d_book';
$this->view('bookstore/admin/change_zip_file', $vars);
}
/**
*
* @param array $config the configuration array
* @return string
*
*/
private function upload($config) {
$this->load->library('upload', $config);
if (!$this->upload->do_upload("file")) {
return $uploadData['file_name'] = NULL;
} else {
$uploadData = $this->upload->data();
log_message('debug', 'file has been uploaded ok - file name is ' . $uploadData['file_name']);
return $uploadData['file_name'];
}
}
答案 0 :(得分:1)
在传递的配置数组中将overwrite
设置为true
$vars = array();
$vars['upload_path'] = 'filepath here';
$vars['allowed_types'] = 'zip';
$vars['max_size'] = '30720';
$vars['book_id'] = $book_id;
// add this line
$vars['overwrite'] = true;
// the old file will now get overwritten
$file_name = $this->upload($vars)
答案 1 :(得分:1)
答案 2 :(得分:0)
更好的方法是检查文件的md5或sha1校验和。
如果两个用户将两个具有相同名称的不同文件上传到服务器,则服务器上的文件将被覆盖,并且不可能仅通过名称来压缩文件。
此外,它可以在PHP中轻松完成。