删除临时文件并在drupal中确认上传


Remove temp file and confirm upload in drupal

我有两个问题。

1) 当我测试我的文件上传时,我会一遍又一遍地上传相同的文件。但是drupal在每个文件的末尾添加了一个递增的数字。这很好,但我宁愿覆盖旧文件。我应该使用file_copy()以外的其他方法吗?我知道drupal对上传的所有文件都有内部参考。我不需要drupal为我保留推荐信。

2) 我正在将文件名添加到数据库中(带有我自己的附加信息),如果文件名已经存在,我该如何写:

if (file_exists) {
 confirmation('do you still want to upload this file?');
 // if yes foo_file_submit($form, &$form_state, 'confirmed');
} else {
 foo_file_submit($form, &$form_state);
}

到目前为止我有什么

function foo_file_validate($form, &$form_state) {
  $file = file_save_upload('file', array(
    //'file_validate_is_image' => array(), // Validates file is really an image.
    'file_validate_extensions' => array('jpg'), // Validate extensions.
  ));
  // If the file passed validation:
  if ($file) {
    // Prepare the file to upload
    $filepath = 'public://foo/files';
    file_prepare_directory($filepath, FILE_CREATE_DIRECTORY); // Create the folder if it doesn't exist
    // Move the file, into the Drupal file system
    if ($file = file_copy($file, $filepath)) {
      // Save the file for use in the submit handler.
      $form_state['storage']['file'] = $file;
    }
    else {
      form_set_error('file', t('Failed to write the uploaded file to the site''s file folder.'));
    }
  }
  else {
    form_set_error('file', t('No file was uploaded.'));
  }
}

如果要覆盖现有文件,可以在调用file_copy函数时传递第三个参数。

默认情况下,Drupal使用FILE_EXISTS_RENAME,它会附加_{incrementing number},直到文件名是唯一的。

在您的情况下,它将是:

file_copy($file, $filepath, FILE_EXISTS_REPLACE)

如果您在自定义表(文件名)中添加已上传的文件,为什么不对文件名执行查询以验证它是否存在?或者您可以使用与Drupal相同的逻辑:

$uri = 'public://yourfile.docx';
if (file_exists($uri)) {
  // Do something
}