如何通过JavaScript实现文件上传时自动区分视频与图片并生成对应HTML标签
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/')anduploadedFile.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 overinput.filesinstead 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

