how to download an image from firebase storage then reupload it but with different name using JavaScript

Viewed 64
// Create a reference with an initial file path and name
        const pathReference = sRef(st, 'RealTime_Recipes_Images/' + localStorage.getItem("rec_title_val") + '.png');

        var blob;

        getDownloadURL(pathReference)
        .then((url) => {

          console.log(url);

          // This can be downloaded directly:
          const xhr = new XMLHttpRequest();
          xhr.responseType = 'blob';
          xhr.onload = (event) => {
             blob = xhr.response;
          };
          xhr.open('GET', url);
          xhr.send();


        })
        .catch((error) => {
          // Handle any errors
        });
        



        // Create the file metadata
        const metadata = {
        contentType: 'image/png'
       };

       // Upload file and metadata
        const storageRef = sRef(
          st,
          "RealTime_Recipes_Images/" + recipe_title_input.value + ".png"
        );



           // 'file' comes from the Blob or File API
        uploadBytes(storageRef, blob, metadata).then((snapshot) => {
          console.log('Uploaded a blob or file!');
        });

debug console output:

    https://firebasestorage.googleapis.com/v0/b/my-chef-7e1e8.appspot.com/o/RealTime_Recipes_Images%2Ftitle.png?alt=media&token=f4c8f00b-59d6-4f9f-ba3f-9a18e4086ebf
Uploaded a blob or file!

so the url returned successfully and the upload part works good because the new uploaded image appears on the storage but i think its an empty blob because XMLHttpRequest() did not work , so what i can do about it . Thank you in advance

storage image

Chrome Browser Console Output:

Access to XMLHttpRequest at 'https://firebasestorage.googleapis.com/v0/b/my-chef-7e1e8.appspot.com/o/RealTime_Recipes_Images%2Ftitle.png?alt=media&token=f4c8f00b-59d6-4f9f-ba3f-9a18e4086ebf' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

          GET https://firebasestorage.googleapis.com/v0/b/my-chef-7e1e8.appspot.com/o/RealTime_Recipes_Images%2Ftitle.png?alt=media&token=f4c8f00b-59d6-4f9f-ba3f-9a18e4086ebf net::ERR_FAILED 200

Issue fixed : follow this link : Firebase Storage Access to fetch at '..' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

2 Answers

Firebase SDK now has a getBlob() function that you can use to download a file directly instead of getting an URL first. This also prevents users from sharing any URL with others.

import { storage } from '../path/to/firebase' // where firebase is initialized
import { getBlob, ref } from 'firebase/storage'

const storageRef = ref(storage, 'file/path.png')
const blob = await getBlob(storageRef)

const url = URL.createObjectURL(blob)
window.open(url)

Try this :

getDownloadURL(pathReference).then((url) => {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function (e) {
    var blob = e.currentTarget.response;
    var content = e.currentTarget.getResponseHeader('Content-Disposition');
    var fileName = content.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)[1];
    savefile(blob, fileName);
}
xhr.send();
})

and write a function with name savefile (outside the ) like this :

savefile(blob, fileName) {
    var a = document.createElement('a');
    a.href = window.URL.createObjectURL(blob);
    a.download = fileName;
    a.dispatchEvent(new MouseEvent('click'));
}

Hope this helps you!

Related