首页 > 解决方案 > 如何使用 React JS 将 MP3 文件上传到 Firebase-Firestore 数据库?

问题描述

我实际上有两个问题,第一个是关于我的代码。二是关于如何通过react将mp3文件上传到Firestore云数据库。

以下代码应该是在云存储集合中轻松添加新文档的表单:

import React, {useState} from 'react';
import db from '../index';

const AddSongs = () => {
    const [song, setSong] = useState('');
    const [artist, setArtist] = useState('');
    const [src, setSrc] = useState('');


    const inSubmit = (e) =>{

        e.preventDefault();

        let songBase = db.collection('songs');
        let data = {song, artist, src}

        songBase
            .add(data)

    }


    return ( 
        <div>
            <form onSubmit={inSubmit}>
                <label>
                    Add Your Track
                </label>
                <input type="text" placeholder="Name of the track" value={song} onChange={e => 
                 setSong(e.target.value)} />
                <input type="text" placeholder="Name of the artist" value={artist} onChange={e => 
                 setArtist(e.target.value)} />
                <input type="file" value={src} onChange={e => setSrc(e.target.value)} />
                <div>
                    <input type="submit" value="add it" />
                </div>
            </form>
        </div>
    );
}

export default AddSongs;

并且文档作为具有歌曲、艺术家和 src 属性的普通文档成功添加到云存储中。这是另一个代码,它应该在集合中获取当前数据并将其呈现给 jsx div

import React, {useState} from 'react';
import db from '../index';

const SongList = () => {
    const [list, setList] = useState([])

    let songbase = db.collection('songs')

    songbase.onSnapshot(snapshot =>{
        snapshot.docs.forEach(doc =>{
            setList([...list, {song: doc.song, artist: doc.artist, src: doc.src, id: Math.random(0,1)}])
        })
    })

    const renderedList = list.length ? (list.map(songItem =>{
        return(
            <div key={songItem.id}>
                <span>{songItem.song}</span>
                <audio controls>
                    <source src={songItem.src} type="audio/mpeg" />
                </audio>
                <span>{songItem.artist}</span>
            </div>
        )
    })) : (<h1>nope !</h1>)
    return ( 
        <div>
            {renderedList}
        </div>
     );
}

export default SongList;

然后这里发生的是songItem(在一个空的jsx中渲染)不断重复自己并不断向下滚动..!

第二个问题是如何将 mp3 文件从我的本地设备添加到 firebase 云存储,因为 (src) 将 mp3 文件路径作为字符串添加到 doc 属性中,例如:C:\fakepath\Black Sabbath - Falling off the世界的边缘(带歌词).mp3。

对不起,很长的问题,您的帮助将不胜感激。

标签: javascriptreactjsfirebasegoogle-cloud-firestore

解决方案


尝试使用react-firebase-file-uploader包。

它由像这样的道具组成storageRef - A reference to the firebase storage folder, where the file should be saved.

onUploadStart, onProgress, onUploadSuccess, onUploadError, filename, metadata, randomizeFilename, maxHeight, maxWidth和许多其他有用的道具。

这是更多详细信息的参考链接。点击这里


推荐阅读