Following the very helpful flow chart posted above, the following code worked for me in Wix Studio. You’ll need to replace the Account Name and Container Name with your actual Blob Storage details. You’ll also need to generate a SAS token and insert here (or store and fetch from Wix Secrets Manager for better security). You’ll also need to set Resource Sharing (CORS) on the Azure side.
For the iFrame you create on your Wix Studio page (label it #htmlUploader) insert the following HTML code:
<!DOCTYPE html>
<html>
<head>
<script type="module">
import { BlobServiceClient } from "https://esm.run/@azure/storage-blob@12.26.0";
async function uploadFile() {
const fileInput = document.getElementById("fileInput");
const file = fileInput.files[0];
if (!file) {
alert("Please select a file to upload.");
return;
}
const accountName = "<STORAGE_ACCOUNT>"; // your storage account
const containerName = "<CONTAINER_NAME>"; // your container name
const sasToken = "<SAS_TOKEN>"; // your generated SAS token
try {
// Create the BlobServiceClient
const blobServiceClient = new BlobServiceClient(
`https://${accountName}.blob.core.windows.net?${sasToken}`
);
// Get the container client
const containerClient = blobServiceClient.getContainerClient(containerName);
// Generate a unique blob name
const blobName = `${Date.now()}-${file.name}`;
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
// Upload the file
const uploadResponse = await blockBlobClient.uploadBrowserData(file);
console.log("Blob uploaded successfully:", uploadResponse);
// Notify parent
window.parent.postMessage(
{
status: "success",
fileName: file.name,
blobUrl: blockBlobClient.url,
},
"*"
);
} catch (error) {
console.error("Error uploading file to Azure Blob Storage:", error);
window.parent.postMessage(
{
status: "error",
message: error.message,
},
"*"
);
}
}
// Expose the function to call it from the button
window.uploadFile = uploadFile;
</script>
</head>
<body>
<h3>Upload File to Azure Blob Storage</h3>
<input type="file" id="fileInput" />
<button onclick="uploadFile()">Upload</button>
</body>
</html>
Then attach this code to the Wix Studio page, replacing #test49 with the ID of a text element that you create on the page (suggest initial text reads “Upload status: Not started” or similar):
$w("#htmlUploader").onMessage((event) => {
const data = event.data;
if (data.status === "success") {
console.log("File uploaded successfully:", data.blobUrl);
$w("#text49").text = `File uploaded successfully! File URL: ${data.blobUrl}`;
} else if (data.status === "error") {
console.error("File upload failed:", data.message);
$w("#text49").text = `File upload failed: ${data.message}`;
}
});