Search code examples
azureauthenticationblobstorage

Azure Blob Storage - upload a document using js


<!DOCTYPE html>
                <html>
                <head>
                    <title>File Upload to Azure Blob Storage</title>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.min.js"></script>
                </head>
                <body>
                    <div class="header">
                        <span class="header-text">Document Request Analyzer</span>
                    <div class="search-container">
                        <input type="text" class="search-bar" placeholder="Search for specific request...">
                    </div>
                    </div>

                    <div class="upload-container">
                        <!--<div class="upload-icon">&#128193;</div>-->
                        <div class="drop-area" id="dropArea">
                            <span>Drag and Drop<br>Document<br>Request</span>
                        </div>
                            <button id="uploadButton" class="btn">Extract Request</button>
                            <canvas id="pdfPreviewCanvas" class="preview-canvas"></canvas>
                    </div>

                    <script>
                        const dropArea = document.getElementById('dropArea');
                        const uploadButton = document.getElementById('uploadButton');
                        const pdfPreviewCanvas = document.getElementById('pdfPreviewCanvas');
                        const fileInput = document.createElement('input');

                        fileInput.type = 'file';
                        fileInput.accept = '.pdf';
                        fileInput.style.display = 'none';
                        document.body.appendChild(fileInput);

                        dropArea.addEventListener('dragenter', (e) => {
                            e.preventDefault();
                            dropArea.classList.add('hover');
                        });

                        dropArea.addEventListener('dragover', (e) => {
                            e.preventDefault();
                        });

                        dropArea.addEventListener('dragleave', () => {
                            dropArea.classList.remove('hover');
                        });

                        dropArea.addEventListener('drop', (e) => {
                            e.preventDefault();
                            dropArea.classList.remove('hover');
                            const file = e.dataTransfer.files[0];
                            fileInput.files = e.dataTransfer.files;
                            handleFileUpload(file);
                        });

                            uploadButton.addEventListener('click', () => {
                            const file = fileInput.files[0];
                            handleFileUpload(file);
                        });


                        async function handleFileUpload(file) {
                            if (!file) {
                                console.error('No file selected.');
                                return;
                            }

                            const accountName = 'test';
                            const containerName = 'test1234';
                            const storageAccessKey = 'test';

                            const currentDate = new Date();
                            const expiryDate = new Date(currentDate);
                            expiryDate.setMinutes(currentDate.getMinutes() + 5);
                            const sasToken = 'testing';
                            const blobName = file.name;
                            const uploadUrl = `https://${accountName}.blob.core.windows.net/${containerName}/${blobName}${sasToken}`;

                            const headers = new Headers();
                            headers.append('x-ms-blob-type', 'GeneralPurposeV2');
                            headers.append('x-ms-date', new Date().toUTCString());
                            headers.append('Content-Length', 0);
                            headers.append('x-ms-version', '2020-04-08');
                            headers.append('Authorization', sasToken);

                            // const formData = new FormData();
                            // formData.append('file', file);

                            const requestOptions = {
                                method: 'PUT',
                                headers: headers,
                                body: file
                            };

                            try {
                                const response = await fetch(uploadUrl, requestOptions);

                                if (response.ok) {
                                    console.log('File uploaded successfully');
                                } else {
                                    console.error('Error uploading file:', response.statusText);
                                }
                            } catch (error) {
                                console.error('An error occurred:', error);
                            }



                            // Display uploaded PDF preview
                            const pdfUrl = URL.createObjectURL(file);
                            const loadingTask = pdfjsLib.getDocument(pdfUrl);

                            try {
                                const pdfDocument = await loadingTask.promise;
                                const firstPage = await pdfDocument.getPage(1);

                                const viewport = firstPage.getViewport({ scale: 1 });
                                pdfPreviewCanvas.width = viewport.width;
                                pdfPreviewCanvas.height = viewport.height;

                                const canvasContext = pdfPreviewCanvas.getContext('2d');
                                const renderContext = {
                                    canvasContext,
                                    viewport,
                                };
                                await firstPage.render(renderContext).promise;

                                pdfPreviewCanvas.style.display = 'block';
                            } catch (error) {
                                console.error('Error rendering PDF:', error);
                                pdfPreviewCanvas.style.display = 'none';
                            }



                        }
                    </script>
                </body>
                </html>

"The errors I am getting using the above code are as follows. I don't know what I am missing

I have checked the permission of my blob storage container and my account and they all seem to be the way they should be

400 (Authentication information is not given in the correct format. Check the value of Authorization header.)

Error uploading file: Authentication information is not given in the correct format. Check the value of Authorization header."


Solution

  • Few changes needed in your code:

    • Remove authorization header from your request headers as it is not needed. You have already included authorization information in your upload URL when you included the SAS token.
    • You have specified incorrect value for x-ms-blob-type request header. It should be BlockBlob.
    • Remove all other request headers as they are not needed. Only request header you would need to include is x-ms-blob-type.