You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Simple Ajax Uploader插件获取文件对象以预获取图片尺寸?

获取Simple Ajax Uploader选中图片的尺寸解决方案

Hey there! I’ve dealt with this exact issue with Simple Ajax Uploader before—since the plugin doesn’t expose the raw File object by default, we need to dig a little into how it handles the file input to grab the image dimensions pre-upload. Here’s how to do it:

1. Access the Native File Input Element

First, you’ll need to get a reference to the actual file input control that the plugin uses. From looking at the plugin’s source, it stores this in a property called _input (you might have spotted this variable when checking the code). We can use this to fetch the selected File object.

2. Use FileReader & Image to Get Dimensions

Image dimensions are only available once the image is loaded, so we’ll use HTML5’s FileReader to convert the file to a data URL, then load it into an Image object to extract width and height.

Example Implementation

Here’s how to integrate this into your plugin’s onSubmit callback, including handling the asynchronous load flow:

// Initialize your uploader
const uploader = new ss.SimpleUpload({
  // Your existing config (button, upload endpoint, etc.)
  button: '#upload-btn',
  url: '/your-upload-api',
  
  onSubmit: function(filename, extension, fileSize) {
    const self = this;
    const fileInput = this._input; // Reference the plugin's internal file input
    
    // Skip non-image files
    if (!fileInput.files || !fileInput.files[0] || !fileInput.files[0].type.startsWith('image/')) {
      return true; // Let non-image files upload normally
    }

    const selectedFile = fileInput.files[0];
    const reader = new FileReader();

    reader.onload = function(e) {
      const img = new Image();
      
      img.onload = function() {
        // Successfully fetched dimensions!
        const imgWidth = img.width;
        const imgHeight = img.height;
        
        console.log(`Image dimensions: ${imgWidth}px x ${imgHeight}px`);
        
        // Store dimensions for later use (e.g., in the onComplete callback)
        uploader.imageDimensions = { width: imgWidth, height: imgHeight };
        
        // Resume the upload process (we paused it by returning false earlier)
        self.startUpload();
      };
      
      img.src = e.target.result; // Load the data URL into the image element
    };

    reader.readAsDataURL(selectedFile); // Convert the file to a usable data URL
    
    // Return false to pause the default upload flow until we get dimensions
    return false;
  },
  
  // Optional: Use the stored dimensions after upload completes
  onComplete: function(filename, response) {
    if (this.imageDimensions) {
      console.log(`Uploaded image size: ${this.imageDimensions.width}x${this.imageDimensions.height}`);
    }
  }
});

3. Alternative: Event Delegation (No Plugin Internal Dependencies)

If you want to avoid relying on the plugin’s internal _input property (in case it changes in future updates), use event delegation to listen for file selections directly:

// Listen for changes on any file input used by the plugin
document.addEventListener('change', function(e) {
  // Adjust the selector to match the plugin's file input class/id
  if (e.target.classList.contains('ss-upload-input')) {
    const file = e.target.files[0];
    
    if (file && file.type.startsWith('image/')) {
      const reader = new FileReader();
      
      reader.onload = function(evt) {
        const img = new Image();
        img.onload = function() {
          console.log(`Selected image dimensions: ${img.width}x${img.height}`);
          // Store these dimensions somewhere accessible to your upload logic
        };
        img.src = evt.target.result;
      };
      
      reader.readAsDataURL(file);
    }
  }
});

Key Notes

  • The startUpload() method is part of the Simple Ajax Uploader API—it resumes the upload after we’ve fetched the dimensions.
  • Always validate that the file is an image before attempting to load it, to avoid errors with non-image files.
  • Since FileReader and image loading are asynchronous, we have to pause the default upload flow (by returning false in onSubmit) and resume it once we have the dimensions.

内容的提问来源于stack exchange,提问作者Teshan N.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:04:19