I need to send a file(PDF) from my website to an external API to be processed and have a response from that distant service.
Context
Visitors need to upload a pdf file to an online service so the PDF is processed by that service and JSON is returned with the file details. Then I’ll use that JSON to design a form for complementary information about that file.
From what I understand there are 2 ways of doing that:
-
Write the upload button in HTML (via HTMLcomponent/webComponent) to send the PDF directly to the third party API (what about security then?) But I’ve got CORS issue.
-
Upload the file via Wix’s upload button and send the file from the backend with fetch.
I’ve been looking around the forum but the only post I found is https://www.wix.com/corvid/forum/community-discussion/upload-files-directly-from-public-to-aws-s3 (@Yisrael (Wix))but that went nowhere.
Question
How can I send a file (hosted in a collection / uploaded to the media manager) to another service from the Wix’s backend?
Hey kentin I will copy paste my answer here just if it helps for anyone else
The External server accept Multipart and to send uploaded file to that external server use the following code in the backend
The code is not complete
It’s just give an idea based on your server URL you will need to modify the header and server url
Multi-part fetch can be done using nodejs too
but You will need to install “form-data” npm
Which is available in wix
i checked it
and here is an example and the doc
form-data: https://www.npmjs.com/package/form-data
import {fetch, getJSON} from "wix-fetch";
const FormData = require("form-data");async function uploadFile(url) {
// convert Wix URL to https:
// => You will need to write the function
// convert the file to readable stream
let fileUrl = removeWixUrl(url);
let blobRes = await fetch(fileUrl);
let blob = await blobRes.blob();
let toSend = {
something: "else",
file: blob.stream()
}
let payload = getFormData(toSend);
console.log({payload, toSend});
let res = await fetch("serverURL" , {
method:"POST" ,
headers: {
'Content-Type': "multipart/form-data" // or try this application/x-www-form-urlencoded
},
body: payload
});
console.log({res})
let json = await res.json();
return json;
}
function getFormData(data) {
if(data === undefined) return;
let {something, file} = data;
let formdata = new FormData();
formdata.append("something", something);
formdata.append("file", file); return formdata;
}
function removeWixUrl() {
return "fix me"
}