wordpress用js实现文件上传并限制文件类型

Published
2023-03-02
浏览次数 :  118

function uploadImage(event) {
  event.preventDefault();
  
  const formData = new FormData();
  const fileInput = document.getElementById('myFile');
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
  
  // Check if the selected file is an image file
  if (allowedTypes.includes(fileInput.files[0].type)) {
    formData.append('myFile', fileInput.files[0]);
  
    // Use the WordPress Media Library API to upload the image
    wp.media.upload({
      files: formData,
      beforeSend: function() {
        // Do something before the upload starts
      },
      success: function(response) {
        // Handle the server response here
      },
      error: function(error) {
        // Handle any errors here
      }
    });
  } else {
    alert('Please select an image file');
  }
}

  • 标签1
  • 标签1
  • 标签1
Top