Can' t delete image from Firebase Storage REACT 2022 - javascript

I have this code from firebase documentation on my firebase file
export async function deleteImage(docId){
// Create a reference to the file to delete
const desertRef = ref(storage, `images/${docId}`);
await deleteObject(desertRef).then(() => {
swal("GOOD", "success");
}).catch((error) => {
swal("error!", "error");});
}
➡️ And i have this code for upload and download URL image on my Dashboard View
async function handleOnChangeProfileImage(e) {
console.log(e.target);
setLoading(true) // Setloading to true
var fileList = e.target.files;
var fileReader = new FileReader();
if (fileReader && fileList && fileList.length > 0) {
fileReader.readAsArrayBuffer(fileList[0]);
fileReader.onload = async function () {
var imageData = fileReader.result;
const res = await setUserProfilePhoto(currentUser.uid, imageData);
if (res) {
const tmpUser = { ...currentUser };
tmpUser.profilePicture = res.metadata.fullPath;
setCurrentUser({ ...tmpUser });
await updateUser(tmpUser);
const url = await getProfilePhotoUrl(currentUser.profilePicture);
setProfileUrl(url);
//updateUserProfilePhoto(currentUser.uid, res.fullPath);
}
};
}
}
➡️ And this is in html
<img className="mb-3 lazyload" key={profileUrl} srcSet={profileUrl} data-src={userImg}
width={200} alt="web.app" />
<Button onClick={handleOpenFilePicker} variant="primary"><FontAwesomeIcon icon={faUpload} /> Upload</Button>
<Button onClick={deleteImage} variant="danger"><FontAwesomeIcon icon={faDeleteLeft}/> Delete</Button>
I can upload an image successfully, but i want to delete the user's profile image with a OnClick event, and for that I use his docId as a reference, but the result is negative, what else do I have to create or do to delete the uploaded image? Hope you help me!! Thanks a lot!

Related

400 Bad request MP4 (Express, Node, React,mongoDB )

I am trying to stream a mp4 file that is on my computer. I am able to upload and delete the files. When the upload completes and click the link. it routes me to the page and I only see {}. and I get the following errors:
GET http://localhost:8000/read/c94e2bfe215bb8821c5c8dc22c8dc1b4.mp4 400 (Bad Request)
favicon.ico:1 GET http://localhost:8000/favicon.ico 404 (Not Found)
I even uploaded a picture to see to check if the mp4 file was too big, but the picture did not load as well.
Here is my code for my server:
// route for streaming a file
app.get('/read/:filename',async(req,res)=>{
const{filename}= req.params
try{
const readstream = await gfs.createReadStream({filename})
res.header("Content-Type","video/mp4");
res.header("X-Content-Type-Options", "nosniff");
res.header("Accept-Ranges", "bytes");
res.header("Content-Length",903746);
readstream.pipe(res)
}catch(err){
res.status(400).send(err)
}
})
Here is the code for react
function App() {
const [file, setFile] = React.useState(null);
const [files, setFiles] = React.useState([]);
const filehandler = (e) => {
if (e.target.files != null || e.target.files[0] != null) {
setFile(e.target.files[0]);
}
};
const uploadFile = async (e) => {
e.preventDefault();
if (file) {
const fd = new FormData();
fd.append("file", file);
const res = await axios.post("http://localhost:8000/upload", fd);
setFiles(files.concat(res.data))
}
};
const fetchFiles = React.useCallback(async () => {
const res = await axios.get("http://localhost:8000/files");
setFiles(res.data);
}, []);
const removeFile = React.useCallback(
async (filename, index) => {
const res = await axios.delete(
`http://localhost:8000/delete/${filename}`
);
if (res.status === 200) {
let temp = [...files];
console.log(temp);
temp.splice(index, 1);
setFiles(temp);
}
},
[files]
);
React.useEffect(() => {
fetchFiles();
}, [fetchFiles]);
return (
<div className="App">
<form className="Form" onSubmit={uploadFile}>
<input type="file" onChange={filehandler} />
<button type="submit">upload</button>
</form>
<div className="Media">
{files.map((file, i) => (
<div key={file._id} className="Item">
<a
className="Link"
href={`http://localhost:8000/read/${file.filename}`}
>
{file.filename}
</a>
<button
type="button"
onClick={() => {
removeFile(file.filename, i);
}}
>
remove
</button>
</div>
))}
</div>
</div>
);}
Your router is sending 400 after catching an exception. Print exception message using console.log(err) in your catch block to determine what exactly goes wrong it try block's code

How to remove images from Firebase Storage?

I'm trying to adapt a React Native project to the new Firebase methods. In it I upload images to Storage and they are added to the App interface. I can also remove these images from the interface as shown in the following code:
const removeImage = (img) => { // delete an image selected by the user
Alert.alert(
"Eliminar imagen",
"¿Estás seguro de eliminar esta imagen?",
[
{
text: "Cancelar",
style: "cancel",
},
{
text: "Eliminar",
onPress: () => {
const result = filter(
formik.values.images,
(image) => image !== img
)
formik.setFieldValue("images", result)
},
},
],
{ cancelable: false }
)
}
The problem is that in this way, they are only removed from my App, while the images are still stored in Firebase. My idea is that when I remove the images from the frontend, they will also be removed from the Firebase Storage.
I have read Firebase documentation, and this would be possible with the deleteObject function
const storage = getStorage();
// Create a reference to the file to delete
const desertRef = ref(storage, 'images/desert.jpg');
// Delete the file
deleteObject(desertRef).then(() => {
// File deleted successfully
}).catch((error) => {
// Uh-oh, an error occurred!
})
I did some test, and I can't get it to work.
I don't know exactly how I should add the Firebase instructions shown here.
How should I implement this function in my code to remove images from Storage?
Thank you
import { getStorage, ref, deleteObject, uploadBytes, getDownloadURL } from "firebase/storage"
export function UploadImagesForm(props) {
const { formik } = props
const [isLoading, setIsLoading] = useState(false) // status for loading
// Function in charge of opening the image gallery
const openGallery = async () => {
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
})
if (!result.cancelled) {
// console.log('buscando imagenes')
setIsLoading(true) // uploading the image
uploadImage(result.uri)
}
}
// function to upload the images to Firebase
const uploadImage = async (uri) => {
const response = await fetch(uri)
const blob = await response.blob()
const storage = getStorage()
const storageRef = ref(storage, `restaurants/${uuid()}`)
// we go to storage where we want to save the images
uploadBytes(storageRef, blob).then((snapshot) => {
// console.log(snapshot)
updatePhotosRestaurant(snapshot.metadata.fullPath)
})
}
// we take the URL in the previous function and set it in the state of the form
const updatePhotosRestaurant = async (imagePath) => {
const storage = getStorage()
const imageRef = ref(storage, imagePath)
const imageUrl = await getDownloadURL(imageRef) // get the url
// code to upload all images without replacing them
// get the current images and add the new ones with the array
formik.setFieldValue("images", [...formik.values.images, imageUrl])
setIsLoading(false)
}
const removeImage = (img) => { // delete an image selected by the user
Alert.alert(
"Eliminar imagen",
"¿Estás seguro de eliminar esta imagen?",
[
{
text: "Cancelar",
style: "cancel",
},
{
text: "Eliminar",
onPress: () => {
const result = filter(
formik.values.images,
(image) => image !== img
)
formik.setFieldValue("images", result)
},
},
],
{ cancelable: false }
)
}
return (
<>
<ScrollView
style={Styles.viewImage}
horizontal
showsHorizontalScrollIndicator={false}
>
<Icon
type="material-community"
name="camera"
color="#a7a7a7"
containerStyle={Styles.containerIcon}
onPress={openGallery}
/>
{map(formik.values.images, (image) => ( // display the images on the screen
<Avatar
key={image}
source={{ uri: image }}
containerStyle={Styles.imageStyle}
onPress={() => removeImage(image)}
/>
))}
</ScrollView>
<Text style={Styles.error}>{formik.errors.images}</Text>
<LoadingModal show={isLoading} text="Subiendo la imagen" />
</>
)
}
I finally figured out where to implement the deleteObject function in my file to make it all work.
You can delete the images from the Application and Firebase Storage at the same time.
I found a React expert who helped me with this.
As the Firebase documentation says:
To delete a file, first create a reference to that file.
( const imageRef = ref(storage, img ))
Firebase explains it like this:
import { getStorage, ref, deleteObject } from "firebase/storage";
const storage = getStorage();
// Create a reference to the file to delete
const desertRef = ref(storage, 'images/desert.jpg');
Then call the delete() method, (in my case: deleteObject(imageRef) ), for that reference, which will return either a Promise that resolves, or an error if the Promise is rejected.
import { getStorage, ref, deleteObject } from "firebase/storage";
const storage = getStorage();
// Create a reference to the file to delete
const desertRef = ref(storage, 'images/desert.jpg');
// Delete the file
deleteObject(desertRef).then(() => {
// File deleted successfully
}).catch((error) => {
// Uh-oh, an error occurred!
});
I just hope this can help other users who are in my situation learning Firebase
I show. the complete file so that they do not have the doubts that I had, which was the correct place where I should place the Firebase methods
const storage = getStorage()
const imageRef = ref(storage, img)
deleteObject(imageRef).then(() => { // also remove the image from Firebase
console.log("la imagen se elimino");
}).catch((error) => {
console.log("ocurrio un error: ", error)
})
Thanks to #FrankvanPuffelen and #BhavyaKoshiya who tried to help.
import { getStorage, ref, uploadBytes, getDownloadURL, deleteObject } from 'firebase/storage'
import { v4 as uuid } from 'uuid'
import { map, filter } from 'lodash'
import { LoadingModal } from '../../Shared/LoadingModal/LoadingModal'
import Styles from './Styles'
export function UploadImagesForm(props) {
const { formik } = props
const [isLoading, setIsLoading] = useState(false) // status for loading
// Function in charge of opening the image gallery
const openGallery = async () => {
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
})
if (!result.cancelled) {
// console.log('buscando imagenes')
setIsLoading(true) // uploading the image
uploadImage(result.uri)
}
}
// function to upload the images to Firebase
const uploadImage = async (uri) => {
const response = await fetch(uri)
const blob = await response.blob()
const storage = getStorage()
const storageRef = ref(storage, `restaurants/${uuid()}`)
// we go to storage where we want to save the images
uploadBytes(storageRef, blob).then((snapshot) => {
// console.log(snapshot)
updatePhotosRestaurant(snapshot.metadata.fullPath)
})
}
// we take the URL in the previous function and set it in the state of the form
const updatePhotosRestaurant = async (imagePath) => {
const storage = getStorage()
const imageRef = ref(storage, imagePath)
const imageUrl = await getDownloadURL(imageRef) // get the url
// code to upload all images without replacing them
// get the current images and add the new ones with the array
formik.setFieldValue("images", [...formik.values.images, imageUrl])
setIsLoading(false)
}
const removeImage = (img) => { // delete an image selected by the user
Alert.alert(
"Eliminar imagen",
"¿Estás seguro de eliminar esta imagen?",
[
{
text: "Cancelar",
style: "cancel",
},
{
text: "Eliminar",
onPress: async () => {
const result = filter(
formik.values.images,
(image) => image !== img
)
formik.setFieldValue("images", result)
**// THIS IS THE CODE I ADDED FROM FIREBASE**
const storage = getStorage()
const imageRef = ref(storage, img)
deleteObject(imageRef).then(() => { // also remove the image from Firebase
console.log("la imagen se elimino");
}).catch((error) => {
console.log("ocurrio un error: ", error)
})
**// END OF THE CODE I ADDED FROM FIREBASE**
},
},
],
{ cancelable: false }
)
}
Great explanation! If anyone has the ref URLs stored in state already, I added the below to my useImages hook and it worked great.
const storage = getStorage();
const deleteImg = (refUrl) => {
const imageRef = ref(storage, refUrl)
deleteObject(imageRef)
.catch((error) => {
console.log("Failed to delete image: ", error)
})
}
You can try this
let imageRef = storage.refFromURL(URL);
imageRef.delete()

Convert multiple images to base 64 using single function

I'm working on a problem where I have to take three images as input from the user and have to send them to the backend by converting them into Base64. I know how to do it for a single input file but can't work my way around for multiple inputs.
I want to have a single function that can convert the images to Base64 & store the value of each image in a separate variable. Please help me out with this.
Following is the code I'm using for single input i.e. First Image.
HTML CODE
<div class="first_div">
<label for="first_image">First Image</label>
<input name="first_image" type="file" accept="image/*" id="first_image" class="img_file">
</div>
<div class="second_div">
<label for="second_image">Second Image</label>
<input name="second_image" type="file" accept="image/*" id="second_image" class="img_file">
</div>
<div class="third_div">
<label for="third_image">Third Image</label>
<input name="third_image" type="file" accept="image/*" id="third_image" class="img_file">
</div>
<button onclick="submitImages()">Submit</button>
JAVASCRIPT CODE
let encoded_image;
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
encoded_image = reader.result;
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
const submitImages = () => {
var files = document.getElementById('first_image').files[0];
if (files.length > 0) {
getBase64(files[0]);
}
const formData = new URLSearchParams(new FormData());
formData.append("first_image", encoded_image);
fetch(API CALL HERE)
}
I want to create a function that takes input from all three fields, converts them to Base64 & stores in a variable. So that I can append it to form data.
Select all inputs, loop and get base64 of each file
Try this
const getBase64 = (file) =>
new Promise((resolve, reject) => {
console.log(file);
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = (err) => reject(err);
});
const submitImages = async () => {
const imageInputs = document.querySelectorAll("input");
const images = await Promise.all(
[...imageInputs].map((imageInput) =>
imageInput?.files?.[0] ? getBase64(imageInput.files[0]) : null
)
);
console.log(images);
};
This example is in React but you can easily modify it to standard javascript.
If it's standard javascript just change const [images, setImages] = useState([]); into let images = [].
const [images, setImages] = useState([]);
const formatImage = async() => {
try {
for (let i = 0; i < e.target.files.length; i++) {
const reader = new FileReader();
reader.readAsDataURL(e.target.files[i]);
reader.onload = (readerEvent) => {
images.push(readerEvent.target ? .result);
};
}
} catch (error) {
console.log(error);
}
};
<input type="file" multiple onChange={formatImage} />
And here is an example of putting these images on Firebase Firestore and again if it's standard javascript change setImages([]) to images = []
const addImage = async() => {
try {
Promise.all(
images.map(
async(file: any) =>
await addDoc(collection(db, "images"), {
image: file,
date: Timestamp.now(),
})
)
);
setImages([]);
} catch (error) {
console.log(error);
}
};

How to get image filename from Firebase Storage?

I am using the following:
const [allImages, setImages] = useState([]);
const getFromFirebase = () => {
//1.
let storageRef = storage.ref(user1);
//2.
storageRef.listAll().then(function (res) {
//3.
res.items.forEach((imageRef) => {
console.log(imageRef);
imageRef.getDownloadURL().then((url) => {
//4.
setImages((allImages) => [...allImages, url]);
});
});
})
.catch(function (error) {
console.log(error);
});
console.log(allImages);
};
and then displaying via:
<button onClick={getFromFirebase}>Show</button><br/><br/>
<div id="photos">
{allImages.map((image) => {
return (
<div key={image} className="image">
<img className="uploadedfile" src={image} alt="" />
<button className="buttondelete" onClick={() => deleteFromFirebase(image)}>
Delete
</button>
</div>
I realise this is returning the getDownloadURL for the image URL, but how do I also return the image filename?
To get the filename you can use getMetadata:
imageRef.getMetadata().then(metadata => {
// do something with metadata.name
});
You can use the 'getMetaData' method.
import { getStorage, ref, getMetadata } from "firebase/storage";
// Create a reference to the file whose metadata we want to retrieve
const storage = getStorage();
const forestRef = ref(storage, 'images/forest.jpg');
// Get metadata properties
getMetadata(forestRef)
.then((metadata) => {
// Metadata now contains the metadata for 'images/forest.jpg'
})
.catch((error) => {
// Uh-oh, an error occurred!
});
You can refer Firebase Docs - File Metadata for a better understanding
To get the file name and url or download link of the videos or files from the firebase storage you can use these two functions in react and javascript
// function to fetch videos/files from firebase storage
const fetchVideos = async () => {
const storageRef = firebase.storage().ref("storage folder name");
const videos = [];
await storageRef
.listAll()
.then(async function (result) {
result.items.forEach(async function (videoRef) {
// getting the name of the file
const videoName = videoRef.name;
//getting the url of the file -> calling another function for this
const videoUrl = await getVideoUrl(videoRef);
// creating the object with name and url
const videoObj = {
videoName,
videoUrl,
};
console.log("video obj", videoObj);
videos.push(videoObj);
});
})
.catch(function (error) {
// Handle any errors
return [];
});
}
// function to get download url
const getVideoUrl = (imageRef) => {
const videoLink = imageRef
.getDownloadURL()
.then(function (videoUrl) {
// console.log("videoUrl", videoUrl);
return videoUrl;
})
.catch(function (error) {
// Handle any errors
return "";
});
return videoLink;
};

How I can know audio/video duration before uploading?

I need to upload file (audio/video) using default input type='file' and the I should pass duration of the video in api request, how i ca do this?
const uploadFile = async (event) => {
let file = await event.target.files[0];
//here api POST request where i should pass duration
}:
You can get the audio duration with HTMLMediaElement.duration:
async function getDuration(file) {
const url = URL.createObjectURL(file);
return new Promise((resolve) => {
const audio = document.createElement("audio");
audio.muted = true;
const source = document.createElement("source");
source.src = url; //--> blob URL
audio.preload= "metadata";
audio.appendChild(source);
audio.onloadedmetadata = function(){
resolve(audio.duration)
};
});
}
Then in your function:
const uploadFile = async (event) => {
let file = event.target.files[0];
//here api POST request where i should pass duration
const duration = await getDuration(file);
}:
You just need to create an element based on user input(video/audio) and get the duration property -
const VIDEO = "video",
AUDIO = "audio";
const uploadApiCall = (file, data = {}) => {
// ----- YOUR API CALL CODE HERE -----
document.querySelector("#duration").innerHTML = `${data.duration}s`;
document.querySelector("#type").innerHTML = data.type;
};
let inputEl = document.querySelector("#fileinput");
inputEl.addEventListener("change", (e) => {
let fileType = "";
let file = inputEl.files[0];
if (file.type.startsWith("audio/")) {
fileType = AUDIO;
} else if (file.type.startsWith("video/")) {
fileType = VIDEO;
} else {
alert("Unsupported file");
return;
}
let dataURL = URL.createObjectURL(file);
let el = document.createElement(fileType);
el.src = dataURL;
el.onloadedmetadata = () => {
uploadApiCall(file, {
duration: el.duration,
type: fileType
});
};
});
<form>
<input type="file" accept="video/*,audio/*" id="fileinput" />
<hr />
Type:<span id="type"></span>
<br />
Duration:<span id="duration"></span>
</form>
In Vue 3 JS, I had to create a function first:
const getDuration = async (file) => {
const url = URL.createObjectURL(file);
return new Promise((resolve) => {
const audio = document.createElement("audio");
audio.muted = true;
const source = document.createElement("source");
source.src = url; //--> blob URL
audio.preload = "metadata";
audio.appendChild(source);
audio.onloadedmetadata = function(){
resolve(audio.duration)
};
});
}
The user would select an MP3 file. Then when it was submitted I could call that function in the Submit function:
const handleAudioSubmit = async () => {
console.log('Your Epsiode Audio is being stored... please stand by!')
if (file.value) {
// returns a number that represents audio seconds
duration.value = await getDuration(file.value)
// remove the decimals by rounding up
duration.value = Math.round(duration.value)
console.log("duration: ", duration.value)
// load the audio file to Firebase Storage using a composable function
await uploadAudio(file.value)
.then((downloadURL) => {
// composable function returns Firebase Storage location URL
epAudioUrl.value = downloadURL
})
.then(() => {
console.log("uploadAudio function finished")
})
.then(() => {
// Set the Album Fields based on the album id to Firestore DB
const updateAudio = doc(db, "artist", artistId.value, "albums, albumID.value);
updateDoc(updateAudio, {
audioUrl: audioUrl.value,
audioDuration: duration.value
})
console.log("Audio URL and Duration added to Firestore!")
})
.then(() => {
console.log('Episode Audio has been added!')
router.push({ name: 'Next' })
})
} else {
file.value = null
fileError.value = 'Please select an audio file (MP3)'
}
}
This takes some time to run and needs refactoring, but works provided you allow the async functions the time to finish. Hope that helps!

Categories

Resources