【问题标题】:How to differ two uploads in one form with same upload handling?如何通过相同的上传处理以一种形式区分两次上传?
【发布时间】:2019-03-20 21:54:26
【问题描述】:

我已经为我的插件创建了一个表单,它有两个上传字段;一个用于图像,一个用于 zip 文件。他们都使用相同的上传处理程序,我想将附件 ID 保存到数据库中。问题是它们使用相同的上传处理程序,因此带有附件 ID 的变量的值将始终是最后一个上传字段。最好的方法是如何做到这一点?保存在数组中(第一个索引是第一个字段,第二个索引是第二个字段)?两个上传处理程序可能有点矫枉过正。任何想法如何以一种好的方式解决这个问题?

这是处理上传的函数:

function releases_action(){
    global $wpdb;

    // Upload cover
     $uploadfiles = $_FILES['uploadfiles'];

      if (is_array($uploadfiles)) {

        foreach ($uploadfiles['name'] as $key => $value) {

          // look only for uploded files
          if ($uploadfiles['error'][$key] == 0) {

            $filetmp = $uploadfiles['tmp_name'][$key];

            //clean filename and extract extension
            $filename = $uploadfiles['name'][$key];

            // get file info
            // @fixme: wp checks the file extension....
            $filetype = wp_check_filetype( basename( $filename ), null );
            $filetitle = preg_replace('/\.[^.]+$/', '', basename( $filename ) );
            $filename = $filetitle . '.' . $filetype['ext'];
            $upload_dir = wp_upload_dir();

            /**
             * Check if the filename already exist in the directory and rename the
             * file if necessary
             */
            $i = 0;
            while ( file_exists( $upload_dir['path'] .'/' . $filename ) ) {
              $filename = $filetitle . '_' . $i . '.' . $filetype['ext'];
              $i++;
            }
            $filedest = $upload_dir['path'] . '/' . $filename;

            /**
             * Check write permissions
             */
            if ( !is_writeable( $upload_dir['path'] ) ) {
              $this->msg_e('Unable to write to directory %s. Is this directory writable by the server?');
              return;
            }

            /**
             * Save temporary file to uploads dir
             */
            if ( !@move_uploaded_file($filetmp, $filedest) ){
              $this->msg_e("Error, the file $filetmp could not moved to : $filedest ");
              continue;
            }

            $attachment = array(
              'post_mime_type' => $filetype['type'],
              'post_title' => $filetitle,
              'post_content' => '',
              'post_status' => 'inherit'
            );

            $attach_id = wp_insert_attachment( $attachment, $filedest );
            require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
            $attach_data = wp_generate_attachment_metadata( $attach_id, $filedest );
            wp_update_attachment_metadata( $attach_id,  $attach_data );
          }
        }

}

正如我所说,由于两个上传字段使用相同的功能,$attach_ID 变量将是最新上传的值。

【问题讨论】:

  • 您希望它们保存在数据库的哪个位置,还是只希望返回值?
  • 现在我将 $attach_id 保存到数据库中的字段中。但是,正如我所写,$attach_id 将包含最新上传文件的值。
  • 您正在使用 foreach 循环,因此您可以将 id 保存在循环中,并且它将具有该循环的正确值。查看答案,我附上了关于将代码放置在何处的注释。
  • 所以我应该将它保存到函数内的数据库中?那不会给我一个表格的两个数据库连接吗?必须有更简单的方法吗?也许将它们保存到数组中?
  • 您正在使用的函数已经使用了至少 2 个数据库连接。我不知道你想在哪里保存 id 以及你想如何拉它,但我在下面再放一点数组......

标签: php wordpress file-upload plugins


【解决方案1】:
function releases_action(){
global $wpdb;

// Upload cover
 $uploadfiles = $_FILES['uploadfiles'];

  if (is_array($uploadfiles)) {

    foreach ($uploadfiles['name'] as $key => $value) {

      // look only for uploded files
      if ($uploadfiles['error'][$key] == 0) {

        $filetmp = $uploadfiles['tmp_name'][$key];

        //clean filename and extract extension
        $filename = $uploadfiles['name'][$key];

        // get file info
        // @fixme: wp checks the file extension....
        $filetype = wp_check_filetype( basename( $filename ), null );
        $filetitle = preg_replace('/\.[^.]+$/', '', basename( $filename ) );
        $filename = $filetitle . '.' . $filetype['ext'];
        $upload_dir = wp_upload_dir();

        /**
         * Check if the filename already exist in the directory and rename the
         * file if necessary
         */
        $i = 0;
        while ( file_exists( $upload_dir['path'] .'/' . $filename ) ) {
          $filename = $filetitle . '_' . $i . '.' . $filetype['ext'];
          $i++;
        }
        $filedest = $upload_dir['path'] . '/' . $filename;

        /**
         * Check write permissions
         */
        if ( !is_writeable( $upload_dir['path'] ) ) {
          $this->msg_e('Unable to write to directory %s. Is this directory writable by the server?');
          return;
        }

        /**
         * Save temporary file to uploads dir
         */
        if ( !@move_uploaded_file($filetmp, $filedest) ){
          $this->msg_e("Error, the file $filetmp could not moved to : $filedest ");
          continue;
        }

        $attachment = array(
          'post_mime_type' => $filetype['type'],
          'post_title' => $filetitle,
          'post_content' => '',
          'post_status' => 'inherit'
        );

        $attach_id = wp_insert_attachment( $attachment, $filedest );
        require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
        $attach_data = wp_generate_attachment_metadata( $attach_id, $filedest );
        wp_update_attachment_metadata( $attach_id,  $attach_data );
        // $ids[]= $attach_id;
        // save $attach id here, its correct for this loop, on the next loop it will be different and so on..
      }
    }

return $ids; // or save here serialize() maybe needed depending on how you are saving. 
}

【讨论】:

  • 我不认为用这种方法可以达到解决方案。因为我猜第一次上传将放在第一个索引中,第二次上传在第二个索引中等等。例如,如果第一个上传字段中没有任何上传,我需要第一个索引为空。很难解释,但你做了一个很好的尝试。我现在看到我只需要重新考虑一下我的代码。
  • 如果 $attach id 失败,它将返回 0。所以你可以在你的逻辑中测试你想做的任何事情。或者您可以执行 if($attachid) {$ids[]=$attachid} else {$ids=""} 之类的操作,但如果您有任何问题,请重新考虑您想要做什么并回发
猜你喜欢
  • 2018-12-30
  • 2018-09-28
  • 2016-10-06
  • 1970-01-01
  • 2015-08-06
  • 2022-12-21
  • 1970-01-01
  • 1970-01-01
  • 2013-07-13
相关资源
最近更新 更多