如何从Base64格式的img标签生成可上传的File对象?
No problem! Here's a step-by-step way to turn that Base64 image source into a proper File object that matches what you'd get from a file input:
Step 1: Extract the Base64 data and MIME type from the img tag
First, grab the src attribute of your image element and split it to separate the metadata (which includes the MIME type) from the actual Base64 encoded data.
// Get the image element const imgElement = document.getElementById('id'); const imageSrc = imgElement.src; // Split the src into metadata and Base64 parts const [metadataPart, base64Data] = imageSrc.split(','); // Extract the MIME type (e.g., "image/jpeg") const mimeType = metadataPart.match(/:(.*?);/)[1];
Step 2: Decode the Base64 data into a byte array
Base64 needs to be decoded back into raw binary data. We'll convert it to a Uint8Array which we can use to create a Blob.
// Decode Base64 string to binary characters const byteChars = atob(base64Data); // Convert characters to byte numbers using a cleaner array method const byteNumbers = Array.from(byteChars, char => char.charCodeAt(0)); // Create a Uint8Array from the byte numbers const byteArray = new Uint8Array(byteNumbers);
Step 3: Create a Blob and convert it to a File object
A Blob is the raw binary data container, and we can wrap it into a File object with all the properties you need (name, last modified date, etc.).
// Create a Blob from the byte array const imageBlob = new Blob([byteArray], { type: mimeType }); // Create the File object (customize name and lastModified as needed) const imageFile = new File([imageBlob], "a22919a70cf8458d654642e0bc2cd881.jpg", { type: mimeType, lastModified: 1521393615000 // Use Date.now() for current timestamp if you don't have the original });
Reusable Function
If you need to do this multiple times, wrap it into a concise function:
function base64ImgToFile(imgElement, filename, lastModified = Date.now()) { const [metadataPart, base64Data] = imgElement.src.split(','); const mimeType = metadataPart.match(/:(.*?);/)[1]; const byteArray = new Uint8Array(Array.from(atob(base64Data), char => char.charCodeAt(0))); const blob = new Blob([byteArray], { type: mimeType }); return new File([blob], filename, { type: mimeType, lastModified }); } // Usage example: const myFile = base64ImgToFile(document.getElementById('id'), "my-image.jpg");
This imageFile (or myFile) will have all the same properties as the file object you get from a file input—you can use it directly with FormData for uploads just like any user-selected file.
内容的提问来源于stack exchange,提问作者user6225298

