react firebase image post 400 error on uploading - javascript

I am trying to upload an image to a cloud storage and received an post 400 error
The file is in initialize in another component.
Thanks for help
const projectStorage = getStorage();
useEffect(() => {
const storageRef = ref(projectStorage, file.name);
uploadBytes(storageRef, file).then((snap) => {
let percentage = (snap.bytesTransferred / snap.totalBytes) * 100;
setProgress(percentage);
console.log('File Uploaded');
}, (err) => {
setError(err);
}, async () => {
//this url doesnt change the setstate url becuase it is in seperate score
const url = await storageRef.getDownloadURL();
setUrl(url);
})
}, [file]);

I created a new project on firebase and then change the permissions on the storage rules and its works.

Related

Firebase storage delete image by downloadURL V9

I'm trying to delete an image from Firebase storage in React Native by downloadURL. Also i'm using web V9.
Writing down most essential chuncks of code:
import {
deleteObject,
getStorage,
ref
} from "firebase/storage";
...
// DownloadURL
const photo = "https://firebasestorage.googleapis.com.... ";
const storage = getStorage();
...
const storageRef = ref(storage, photo);
deleteObject(storageRef)
.then(() => {
console.log("File deleted successfully");
})
.catch((error) => {
console.log(error.message);
});
My code is inspired from here and I got this error:
[Unhandled promise rejection: FirebaseError: Firebase Storage: The
operation 'deleteObject' cannot be performed on a root reference,
create a non-root reference using child, such as .child('file.png').
(storage/invalid-root-operation)]
I'm little confused.
Later edit:
My function which upload the image and get the download url:
// uri is returned from "expo-image-picker"
const uploadImageAsync = async (uri) => {
// manipulateAsync imported from 'expo-image-manipulator'
const manipResult = await manipulateAsync(uri, [], {
compress: 0.6,
format: "jpeg",
});
const response = await fetch(manipResult.uri);
const blob = await response.blob();
const imageName = Date.now().toString();
const fileRef = ref(storage, `avatar/${user.uid}/${imageName}.jpg`);
const result = await uploadBytes(fileRef, blob);
getDownloadURL(fileRef).then((snapshot) => {
// downloadURL is added to Redux state to be used later
dispatch(addPhoto(snapshot));
});
};

Firebase v9 uploading image shows only 9 bytes

im using react native and firebase (v9) to upload image to firebase. in the firebase storage, the file was uploaded, but the size is only 9 bytes so it's not opening properly. I'm not sure how to fix this :S
const uploadFiles = (file, name, storeKey) => {
if(!file){
console.log('no file exists')
return;
}
const exe = file.substring(file.lastIndexOf('.'));
const fileName = name + exe;
const storageRef = ref(storage, `/files/${fileName}`);
const uploadTask = uploadBytesResumable(storageRef, file);
uploadTask.on('state_changed', null,
(error) => {
alert(error);
},
() => {
getDownloadURL(uploadTask.snapshot.ref)
.then((URL) => {
setDoc(doc(db, 'Store', storeKey, 'coffeeDB', name), {postImage: URL}, {merge: true});
console.log('url registered')
});
}
)
}
Given that you're calling file.substring(...), it seems that file is a file name. You can't upload a file by just passing its name, as that'd be a security risk. Instead you'll need to pass a Blob | Uint8Array | ArrayBuffer as shown here and here, typically by passing the File reference from which you got the file name.

I'm trying to upload image but image is not adding to cloud firestore, its uploaded on firebase storage But not showing in React app

This is the code for uploading image on React app. Its showing on firebase storage but not added in to cloud firestore. and that's why I am not able to upload any image on React app manually. I've googled and searched so many times but cant fix this.
function Imgupload({username}){
**strong text** const [caption,setCaption]=useState('');
const [image,setImage]=useState(null);
//const [url,setUrl]= useState("");
const [progress,setProgress]=useState(0);
const handlechange = (e)=>{
if(e.target.files[0]){
setImage(e.target.files[0]);
}
};
const handleUpload = () =>{
const uploadTask= storage.ref('images/$ {image.name}').put(image);
uploadTask.on(
"state_change",
(snapshot) =>{
//progress function..
const progress=Math.round(
(snapshot.bytesTransferred/snapshot.totalBytes) * 100
);
setProgress(progress);
},
(error) =>{ //error func..
console.log(error);
alert(error.message);
},
()=>{ //complete func..
storage
.ref("images")
.child(image.name)
.getDownloadURL()
.then (url =>{
//post img on db..
db.collection("posts").add({
timestamp:firebase.firestore.FieldValue.serverTimestamp(),
caption :caption,
imgurl :url,
username :username
});
setProgress(0);
setCaption("");
setImage(null);
});
}
);
}
This is the Error from console:
localhost/:1 Uncaught (in promise) FirebaseError: Firebase Storage: Object 'images/Screenshot (202).png' does not exist. (storage/object-not-found)
{
"error": {
"code": 404,
"message": "Not Found."`enter code here`
}
}
Can't fix this problem. please help.
You have an extra space in the file name here:
const uploadTask= storage.ref('images/$ {image.name}').put(image);
// 👆
You don't have that same space when you call getDownloadURL here:
storage
.ref("images")
.child(image.name)
.getDownloadURL()
So these two code fragments point to different files, which explains why the second fragment can't find the file you uploaded.
I recommend using a single variable to hold the reference, and use that in both fragments:
const imageRef = storage
.ref("images")
.child(image.name);
const uploadTask= imageRef.put(image);
...
imageRef.getDownloadURL()...

Upload .vhd as Page-Blob to azure-blob-storage from Url

i have a bunch of VHD files stored on a private Server, which are accessible through a url.
I am trying upload these vhd files directly to my azure storage account using the azure javascript npm libraries. The vhds have to be uploaded as page-blobs. I tried using the method uploadPagesFromURL() of the pageblobClient but with no success. My code looks roughly like this:
async function uploadVHD(accessToken, srcUrl)
{
try {
// Get credentials from accessToken
const creds = new StorageSharedKeyCredential(storageAccount.name, storageAccount.key);
// Get blobServiceClient
const blobServiceClient = new BlobServiceClient(`https://${storageAccount.name}.blob.core.windows.net`, creds);
// Create Container
const containerClient = blobServiceClient.getContainerClient("vhd-images");
await containerClient.createIfNotExists();
const src = srcUrl.replace('https://', 'https://username:password#');
// Upload to blob storage
const pageBlobClient = containerClient.getPageBlobClient("Test.vhd");
// Get fileSize of vhd
const fileSize = (await axiosRequest(src, { method: "HEAD" })).headers["content-length"];
const uploadResponse = await pageBlobClient.uploadPagesFromURL(src, 0, 0, fileSize);
return uploadResponse;
} catch (error) {
return error;
}
});
It is not possible to upload the Page Blob with your URL directly. You need to read data from the url. Then upload using uploadPages method.
axios.get(URL, {
responseType: 'arraybuffer'
})
.then((response) => {
console.log(response.data)
console.log(response.data.length)
// upload page blob...
}).catch((error) => {
//handle error
});
// uploadPages method
const uploadResponse = pageBlobClient.uploadPages(data, 0, dataLength);

React Native Firebase: I'm trying to upload profile image via cloud storage but the function in 'then()' is not responding

I'm trying to upload profile picture and for this I'm using firebase cloud storage and firebase real-time database, i've to call another function in then() but it's not working for some reason. Please correct my mistake..
uploadImage = async uri => {
const response = await fetch(uri);
const blob = await response.blob();
var FilePath = imageId + '.' + this.state.currentFileType;
storage()
.ref('user/' + userid + './img')
.child(FilePath)
.put(blob)
.then(snap => {
snap.ref.getDownloadURL().then(downloadURL => {
console.log(downloadURL);
this.processUpload(downloadURL);
});
})
.catch(err => {
console.error(err);
});
};
With catch callback, I'm getting this
[TypeError: undefined is not an object (evaluating
'snap.ref.getDownloadURL')]

Categories

Resources