File upload on Azure in React
Code Snippet : Azure sdk
import { BlobServiceClient } from "@azure/storage-blob";
const fileuploader = () => {
const [uploadProgress, setUploadProgress] = useState(0);
const [loading, setLoading] = useState<boolean>(false);
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const uploadFileToAzure = async () => {
setLoading(true);
if (!selectedFile) {
alert("Please select a file!");
return;
}
const blobserviceUrl ="";
const blobServiceClient = new BlobServiceClient(blobserviceUrl);
const containerClient = blobServiceClient.getContainerClient("uploadfiles");
const id = uuid();
const blockBlobClient = containerClient.getBlockBlobClient(
fileType + "/" + id + "-" + selectedFile.name
);
const arrayBuffer = await convertFileToArrayBuffer(selectedFile);
if (!arrayBuffer) {
throw new Error("Array Buffer is not found");
}
const totalBytes = arrayBuffer.byteLength;
let totalBytesSent = 0;
try {
const response = await blockBlobClient.uploadData(arrayBuffer, {
onProgress: (e) => {
const progress = (e.loadedBytes / totalBytes) * 100;
setUploadProgress(progress);
},
blobHTTPHeaders: {
blobContentType: selectedFile?.type,
},
});
if (response) {
setImageUrl(blockBlobClient.url);
}
} catch (error) {
console.error("Error uploading image: ", error);
alert("Failed to upload image. Please try again later.");
}
const newUrl = blockBlobClient.url.split("?sv=")[0];
console.log("this is url", blockBlobClient.url);
// save url to db
db.save({
url: newUrl,
});
setLoading(false);
setSelectedFile(null);
setUploadProgress(0);
};
return (
...
)
}