繁体   English   中英

如何从 React.js 中的 firebase 获取文件

[英]How can I fetch file from firebase in React.js

I have uploading function to firebase with React.js, I use put method for upload images to firebase, now I need to download that picture from firebase, could you help me please? 我上传文件的代码是:

import React, { useState, useEffect } from 'react'
import { storage } from '../../firebase/firebase'

const Upload = () => {

    const [photo, setPhoto] = useState(null)
    const [url, setUrl] = useState(null)


    const imageChangeHandler = (event) => {
        setPhoto(event.target.files[0])
    }

    const fileUploadHandler = () => {

        const uploadTask = storage.ref(`image/${photo.name}`).put(photo);
        uploadTask.on(
            'state-changed',
            snapshot => { },
            error => {
                console.log(error);
            },
            () => {
                storage.ref('image').child(photo.name).getDownloadURL()
                    .then(url => {
                        setUrl(url)
                    })
            }
        )
    }

    return (
        <div className="upload-box">
            <div className="form-upload">
                <input onChange={imageChangeHandler} type="file" className="upload-input" />
                <button onClick={fileUploadHandler} type="submit" value="Send" className="upload-btn">Upload</button>
                <ul>
                    <li>
                        <img width="200px" height="200px" src={url} alt="firebase_uladed_image" />
                    </li>
                </ul>
            </div>
        </div>
    )
    }

     export default Upload

你需要使用 useEffect 从 firebase 像这样

useEffect(()=>{
   fetchApi
   setImage() 
}, [])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM