gpt4 book ai didi

javascript - 如何从 Firebase 存储中删除图像?

转载 作者:行者123 更新时间:2023-12-05 04:27:20 24 4
gpt4 key购买 nike

我正在尝试使 React Native 项目适应新的 Firebase 方法。在其中我将图像上传到存储并将它们添加到应用程序界面。我还可以从界面中删除这些图像,如以下代码所示:

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 }


)
}

问题是这样,它们只是从我的应用程序中删除,而图像仍存储在 Firebase 中。我的想法是,当我从前端删除图像时,它们也会从 Firebase Storage 中删除。

我已阅读 Firebase 文档,这可以通过 deleteObject 函数实现

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!
})

我做了一些测试,但无法正常工作。我不知道我应该如何添加 Firebase instructions shown here .

我应该如何在我的代码中实现此功能以从存储中删除图像?

谢谢

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" />
</>
)
}

最佳答案

我终于找到了在我的文件中实现 deleteObject 函数的位置以使其全部正常工作。您可以同时从应用程序和 Firebase 存储中删除图像。我找到了一位 React 专家帮助我解决了这个问题。

正如 Firebase 文档所说:

要删除文件,首先创建对该文件的引用。

( const imageRef = ref(storage, img ))

Firebase 是这样解释的:

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() 方法(在我的例子中是 deleteObject(imageRef) ),它将返回一个解决的 Promise,或者如果 Promise 被拒绝则返回一个错误。

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!
});

我只是希望这可以帮助像我这样的其他用户学习 Firebase

我显示。完整的文件,这样他们就不会像我一样怀疑,这是我应该放置 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)
})

感谢@FrankvanPuffelen 和@BhavyaKoshiya 的帮助。

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 }
)
}

关于javascript - 如何从 Firebase 存储中删除图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72829824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com