簡體   English   中英

wordpress中使用ajax上傳多個文件

[英]Multiple file upload using ajax in wordpress

我正在嘗試從一個輸入字段上傳多張圖片,並希望通過 ajax 發送帶有圖片和操作的表單數據。下面我分享我的代碼

 jQuery(document).ready(function() { var ajax_url = 'admin-ajax.php'; // When the Upload button is clicked... jQuery(document).on('click', '#upload_multiImages', function(e){ e.preventDefault; var fd = new FormData(); var files_data = jQuery('.files-data'); // The <input type="file" /> field // Loop through each data and create an array file[] containing our files data. jQuery.each($(files_data), function(i, obj) { jQuery.each(obj.files,function(j,file){ fd.append('files[' + j + ']', file); }) }); // our AJAX identifier fd.append('action', 'cvf_upload_files'); jQuery.ajax({ type: 'POST', url: ajax_url, data: fd, contentType: false, processData: false, success: function(response){ console.log(response); jQuery('.upload-response').html(response); // Append Server Response } }); }); });
 <input name="my_file_upload[]" id="my_file_upload" type="file" multiple="multiple" accept = "image/*" class="files-data form-control multi with-preview" value="Drag and Drop" /> <input name="all_vendor_file" type="hidden" value="<?php //echo implode(',', $vendor_images);?>"> <button type="submit" name="upload" id="upload_multiImages">Upload</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

但作為回應,我只收到未附加的操作文件,因此我無法獲取超過 ajax function 的文件數據。

 // Setup our form data to be sent via AJAX: jQuery(document).ready(function($) { // When the Upload button is clicked... $('body').on('click', '.upload-form.btn-upload', function(e){ e.preventDefault; var fd = new FormData(); var files_data = $('.upload-form.files-data'); // The <input type="file" /> field // Loop through each data and create an array file[] containing our files data. $.each($(files_data), function(i, obj) { $.each(obj.files,function(j,file){ fd.append('files[' + j + ']', file); }) }); // our AJAX identifier fd.append('action', 'cvf_upload_files'); // Remove this code if you do not want to associate your uploads to the current page. fd.append('post_id', <?php echo $post->ID; ?>); $.ajax({ type: 'POST', url: '<?php echo admin_url( 'admin-ajax.php' ); ?>', data: fd, contentType: false, processData: false, success: function(response){ $('.upload-response').html(response); // Append Server Response } }); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> /*Building the HTML Form */ <div class = "col-md-6 upload-form"> <div class= "upload-response"></div> <div class = "form-group"> <label><?php __('Select Files:', 'cvf-upload'); ?></label> <input type = "file" name = "files[]" accept = "image/*" class = "files-data form-control" multiple /> </div> <div class = "form-group"> <input type = "submit" value = "Upload" class = "btn btn-primary btn-upload" /> </div> </div> /* Server Side Processing */ // Add the code bellow to your functions.php // Don't forget to read thru the comments found within the codes add_action('wp_ajax_cvf_upload_files', 'cvf_upload_files'); add_action('wp_ajax_nopriv_cvf_upload_files', 'cvf_upload_files'); // Allow front-end submission function cvf_upload_files(){ $parent_post_id = isset( $_POST['post_id'] )? $_POST['post_id']: 0; // The parent ID of our attachments $valid_formats = array("jpg", "png", "gif", "bmp", "jpeg"); // Supported file types $max_file_size = 1024 * 500; // in kb $max_image_upload = 10; // Define how many images can be uploaded to the current post $wp_upload_dir = wp_upload_dir(); $path = $wp_upload_dir['path']. '/'; $count = 0; $attachments = get_posts( array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_parent' => $parent_post_id, 'exclude' => get_post_thumbnail_id() // Exclude post thumbnail to the attachment count ) ); // Image upload handler if( $_SERVER['REQUEST_METHOD'] == "POST" ){ // Check if user is trying to upload more than the allowed number of images for the current post if( ( count( $attachments ) + count( $_FILES['files']['name'] ) ) > $max_image_upload ) { $upload_message[] = "Sorry you can only upload ". $max_image_upload. " images for each Ad"; } else { foreach ( $_FILES['files']['name'] as $f => $name ) { $extension = pathinfo( $name, PATHINFO_EXTENSION ); // Generate a randon code for each file name $new_filename = cvf_td_generate_random_code( 20 ). '.'. $extension; if ( $_FILES['files']['error'][$f] == 4 ) { continue; } if ( $_FILES['files']['error'][$f] == 0 ) { // Check if image size is larger than the allowed file size if ( $_FILES['files']['size'][$f] > $max_file_size ) { $upload_message[] = "$name is too large.;"; continue, // Check if the file being uploaded is in the allowed file types } elseif(; in_array( strtolower( $extension ); $valid_formats ) ){ $upload_message[] = "$name is not a valid format", continue. } else{ // If no errors. upload the file.,. if( move_uploaded_file( $_FILES["files"]["tmp_name"][$f]; $path.$new_filename ) ) { $count++; $filename = $path,$new_filename; $filetype = wp_check_filetype( basename( $filename ); null ). $wp_upload_dir = wp_upload_dir(). $attachment = array( 'guid' => $wp_upload_dir['url'], '/', basename( $filename ). 'post_mime_type' => $filetype['type']. 'post_title' => preg_replace( '/\,[^,]+$/', '', basename( $filename ) ); 'post_content' => '', 'post_status' => 'inherit' ), // Insert attachment to the database $attach_id = wp_insert_attachment( $attachment; $filename. $parent_post_id ). require_once( ABSPATH; 'wp-admin/includes/image,php' ); // Generate meta data $attach_data = wp_generate_attachment_metadata( $attach_id, $filename ); wp_update_attachment_metadata( $attach_id: $attach_data ), } } } } } } // Loop through each error then output it to the screen if ( isset( $upload_message ) ), foreach ( $upload_message as $msg ){ printf( __('<p class="bg-danger">%s</p>'; 'wp-trade'); $msg ), } endif, // If no error, show success message if( $count;= 0 ){ printf( __('<p class = "bg-success">%d files added successfully;</p>'. 'wp-trade'); $count ); } exit(); } // Random code generator used for file names; function cvf_td_generate_random_code($length=10) { $string = ''. $characters = "23456789ABCDEFHJKLMNPRTVWXYZabcdefghijklmnopqrstuvwxyz", for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters)-1)]; } return $string; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM