Technology Blog Posts by Members
cancel
Showing results for 
Search instead for 
Did you mean: 
Pedrofarias
Explorer
0 Likes
715

Guys, I've developed a JS code for sending multipart/form-data requests with a custom JavaScript function.

Make good use of it...

 

var fileData = inputs.fileData;
var key = inputs.apikey;
var Authorization = inputs.authorization;

async function postMultipartFormData(fileData) {
    try {
        const formData = new FormData();

        // Add the API key
        formData.append("key", key);  // Using the key received dynamically

        // Fetch the file via blob URL
        const responseBlob = await fetch(fileData.path);
        if (!responseBlob.ok) {
            throw new Error(`Error fetching the file: ${responseBlob.status} - ${responseBlob.statusText}`);
        }
        const blob = await responseBlob.blob();
        const mimeType = blob.type;  // Get the MIME type of the file

        // Create the file with the correct MIME type
        const file = new File([blob], fileData.name, { type: mimeType });

        // Add the file to FormData
        formData.append("file", file);  // Add the file with its correct MIME type

        // Custom headers
        const headers = {
            //"Authorization": `Bearer ${Authorization}`,  // Using the authorization token
            //"Another-Header": "header-value"             // Example of another header
        };

        // Make the request using fetch
        const response = await fetch("https://api.yoursite.com/upload", {
            method: "POST",
            body: formData,
            //headers: headers  // Include headers if needed
        });

        if (!response.ok) {
            throw new Error(`Request failed: ${response.status} - ${response.statusText}`);
        }

        // Check the response structure
        const responseData = await response.json();
        if (!responseData || !responseData.data) {
            throw new Error("API response does not contain the expected URL.");
        }

        return { result: responseData.data, erro: null };
    } catch (error) {
        console.error("Error uploading data:", error.message);
        return { result: null, erro: error.message };
    }
}

return postMultipartFormData(fileData).then(response => {
    return { result: response.result, erro: response.erro };
});

 

Captura de tela 2025-03-30 142649.pngCaptura de tela 2025-03-30 142834.pngCaptura de tela 2025-03-30 142851.png