I have the below code in my ReactJS file that is to upLoad a file to Firebase.
async function uploadFile() {
console.log('starting UPLOAD ========');
const blob = await fetch(mediaBlobUrl).then((r) => r.blob());
const path = '/recordings/one';
firebase
.storage()
.ref(path)
.put(blob)
.then(function (snapshot) {
console.log('Uploaded complete');
});
console.log(`====> setURL is ${setURL} <=======`);
storage.ref(path).getDownloadURL().then(setURL);
}
The first time the button is clicked I get this error, but the the second time I click it then it works. Not sure what is going on?
Firebase Storage: Object 'recordings/one' does not exist. (storage/object-not-found)
I did notice when it fails this is the URL it is trying to hit (404). Notice the %2 instead of "/"
https://firebasestorage.googleapis.com/v0/b/buerce.appspot.com/o/recordings%2Fone 404
That's because your getDownloadURL method runs before actually uploading file. Both the put and getDownloadURL method returns promises. Your function is async so I'd recommend using await for both upload and getDownloadURL methods just like you are doing on fetch method.
async function uploadFile() {
console.log('starting UPLOAD ========');
const blob = await fetch(mediaBlobUrl).then((r) => r.blob());
const path = '/recordings/one';
await firebase.storage().ref(path).put(blob)
const setURL = await storage.ref(path).getDownloadURL()
console.log(`====> setURL is ${setURL} <=======`);
}
Related
const CreatePost = async () => {
if (imageUpload == null) return;
const imageRef = ref(storage, `images/`);
uploadBytes(imageRef, imageUpload).then((snapshot) => {
getDownloadURL(imageRef).then((url) => {
setImageUrl(url);
console.log(url);
});
});
console.log(url) Works and gives me the correct url but it is not stored in firestore
React useState hook is asynchronous. So, it won't have the URL that you are setting at the time when you're using it. Use the useEffect hook and add your state in the dependence array, and you will always get the updated value.
I'm trying to fetch a .json file from local, and
I get response 200 but with a body response of HTML: "You need to enable JavaScript to run this app."
I have javascript enabled of course.
I don't want to import the file to simulate the real fetch.
How does local fetch work in react? How do I know if the fetch route is right? It doesn't give any useful error hint.
useEffect(() => {
const getData = async () => {
const dataFromLocal = await fetchData();
console.log('dataFromLocal', dataFromLocal);
}
getData();
}, [])
const fetchData = async () => {
const response = await fetch('data.json');
const data = await response.json();
return data;
}
I found how it works:
const response = await fetch('data.json',
{headers:
{'Content-Type': 'application/json','Accept': 'application/json'}
});
just add this headers object to the fetch method and it works
There are only two possibilities based on the code you've shown:
Your server is responding with the contents of an HTML resource (likely index.html) as the response to the request for data.json, or
data.json looks like this, the JSON string you provided:
"You need to enable JavaScript to run this app."
Is data.json in your project's ./public folder?
I want to upload images to FireBase storage and then save the image url to the firebase firestore database. It works 50% of the time but sometimes the url shows up as null.
CODE:
const onUpload = async () => {
setLoading3(true);
for (let i = 0; i < campaignImage.length; i += 1) {
const file = campaignImage[i]
const storageRef = storage.ref()
const fileRef = storageRef.child(file.name)
await fileRef.put(file)
setUrl(await fileRef.getDownloadURL())
db.collection("campaigns").doc(campaignName).update({
images: firebase.firestore.FieldValue.arrayUnion({
name: file.name,
url: url
})
})
}
The file name works perfectly but the url sometimes doesn't show. The image upload is always successful but placing the image url into the firestore collection is not working.
It sounds like setUrl() is a react state hook. When you call it, it will not immediately affect the value of the variable it provides. If you need to use the URL from getDownloadURL(), you should save it to a local variable. The url from the state hook will get its new value after the component renders again.
const downloadUrl = await fileRef.getDownloadURL())
setUrl(downloadUrl)
db.collection("campaigns").doc(campaignName).update({
images: firebase.firestore.FieldValue.arrayUnion({
name: file.name,
url: downloadUrl
})
I am trying to fetch full HTML page content of a single page web application (AngularJS) using puppeteer. But I got only HTML content of header and footer. This code working fine on my local machine but not working on AMI server.
//function for timeout
async function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// function to crawl a html page using a url
async function crawler(url) {
const browser = await puppeteer.launch({
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox']
});
const page = await browser.newPage();
await page.goto(url); //fetch url
await timeout(5000); // wait for 5 second to load full page
const html = await page.evaluate(() => document.documentElement.outerHTML);
await browser.close();
return html;
}
Also tried waitFor and networkidle2 but didn't get proper HTML in result.
Trying to pass the file object to redux action and perform the function inside of an redux action, not sure its the correct way? but basically i want back downloadURL from firebase upload complete so I can show image front end.
createLocation(event) {
event.preventDefault();
const fileObject = this.state.file;
const test = {
fileObject
}
this.props.uploadImage_func(test);
}
and action function:
export function uploadImage_func(fileObject) {
return dispatch => {
const fileName = 'myimage';
const storageRef = firebase.storage().ref('test/' + fileName);
const task = storageRef.put(fileObject);
task.on('state_changed',
function complete(snapshot) {
const downloadURL = task.snapshot.downloadURL;
},
).then(function () {
dispatch(attemptLogin({
...downloadURL
}));
});
}
}
error:
As you can see you have got an error Invalid argument in 'put' at index 0: Expected Blob or File. So first of all you need path exactly File or Blob. If you did right in you createLocation and got file object than you need not to wrap it in const test object more. That action causes unnecessary nesting, so just path fileObject as it is. And more. When you subscribe for firebase UploadTask on event you need to path callback functions and do it in a right order, so try to use next:
uploadTask.on('state_changed',
(snapshot) => {
// here you could log loading information in percents but uploading is not finished yes
console.log((snapshot.bytesTransferred / snapshot.totalBytes) * 100);
},
(error) => console.log(error),
() => {
// And after uploading is complete you could get your download url
console.log('Call save img', uploadTask.snapshot.downloadURL);
}
);
For more information read documentation for Firebase Storage (Upload files)