javascript - 如何使用 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。
对不起,很长的问题,您的帮助将不胜感激。
解决方案
尝试使用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
和许多其他有用的道具。
这是更多详细信息的参考链接。点击这里
推荐阅读
- python - 如何比较执行相同任务的两个函数的效率(谁更快)
- r - 有条件地插入新行并将值添加到 R 中的新行
- node.js - 如何使用护照验证 React 应用程序?
- python - 为什么不能在这个 python 操作中把集合推导放在首位呢?
- javascript - Javascript对象打印为对象对象
- javascript - 反应:TypeError:items.map 不是函数
- javascript - 此错误是否是异步/Gulp 问题:未定义选项属性未定义的值未定义超出范围?
- reactjs - React-admin 的 onSave 方法不传递表单值
- c - 无法将字符添加到分配给“”的字符指针
- javascript - 如何将 js 字符串转换为类似于 AST 树的东西?