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

如何通过JavaScript实现文件上传时自动区分视频与图片并生成对应HTML标签

Solution: Auto-detect File Type & Render with the Correct HTML Tag

Great question! The core of solving this is leaning on the MIME type of the uploaded file—every File object from your input has a built-in type property that tells us exactly whether we’re dealing with an image or video, no manual user selection needed.

Let’s adjust your code to add this logic step by step:

Step 1: Grab the Original File’s MIME Type

Instead of only working with the reader.result data URL, we’ll pull the type directly from the uploaded file (input.files[0]). This is far more reliable than parsing the data URL itself.

Step 2: Generate the Right HTML Tag

Use conditional logic to check if the MIME type starts with image/ or video/, then build the corresponding tag string for your socket message.

Here’s the updated openFile function:

var openFile = function(file) {
  var input = file.target;
  // Get the first uploaded file (loop through input.files if handling multiple)
  var uploadedFile = input.files[0];
  if (!uploadedFile) return;

  var reader = new FileReader();
  reader.onload = function() {
    try {
      var dataURL = reader.result;
      let mediaTag = '';

      // Check MIME type to decide which tag to render
      if (uploadedFile.type.startsWith('image/')) {
        mediaTag = `<img alt="Image Uploaded" style="cursor: zoom-in; border-radius: 4px; width: 16rem" src="${dataURL}">`;
      } else if (uploadedFile.type.startsWith('video/')) {
        mediaTag = `<video controls autoplay="1" alt="Video Uploaded" style="cursor: zoom-in; border-radius: 4px; width: 16rem" src="${dataURL}"></video>`;
      } else {
        // Handle unsupported file types with a user-friendly alert
        Toast.fire({
          icon: 'error',
          title: 'Unsupported file type'
        });
        return;
      }

      Toast.fire({
        title: 'Uploading your File...',
        text: "",
        didOpen: () => {
          Swal.showLoading()
        },
      });
      // Send only the correct tag via socket
      socket.emit('message', mediaTag);
    } catch (err) {
      console.error('Error processing file:', err);
      Toast.fire({
        icon: 'error',
        title: 'Failed to upload file'
      });
    }
  };
  reader.readAsDataURL(uploadedFile);
};

Key Details & Improvements:

  • Reliable Type Detection: uploadedFile.type.startsWith('image/') and uploadedFile.type.startsWith('video/') work for all standard image (JPG, PNG, GIF, etc.) and video (MP4, WEBM, etc.) formats supported by modern browsers.
  • Clean Tag Generation: We only build the tag that matches the file type, so other users won’t get redundant or broken elements.
  • Error Handling: Added checks for unsupported files and general errors, with clear toasts to keep the user experience smooth.
  • Multiple Files (Optional): Since your input has multiple="multiple", you can loop over input.files instead of just taking the first file if you want to support batch uploads.

Quick Note on Data URLs & Sockets:

Since you confirmed data URLs work for socket transmission (unlike blobs), this approach preserves your existing workflow. For very large videos, you might want to explore chunking later, but this solution fits your current needs perfectly.

内容的提问来源于stack exchange,提问作者Cohen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 13:47:38