Firebase Storage存储文本显示为数字而非预期字符串的问题
问题:Firebase Storage上传文本后下载显示数字而非预期字符串
我在React Native项目中使用Firebase Storage存储用户反馈文本,相关代码如下:
import { StyleSheet, Text, View, TextInput} from 'react-native' import React , { useState} from 'react' import { storage} from '../firebase' import { Button } from '@rneui/themed'; import { uploadString } from 'firebase/storage'; import { ref as sRef } from 'firebase/storage'; import 'react-native-get-random-values' import {v1} from 'uuid' const Reviews = ({route}) => { const paramKey = route.params.paramKey1 const paramKey1 = route.params.paramKey2 console.log("Path: " + paramKey) console.log("Shop: " +paramKey1) const feedback = "Post" const [todoDatafb, setToDoDatafb] = useState("") const handlefb = async () => { const fb = sRef(storage, paramKey + `/${feedback + v1()}.txt`); uploadString(fb, todoDatafb).then((snapshot) => { console.log('Uploaded new feedback') }) } console.log(todoDatafb) return ( <View style = {styles.container}> <Text style = {styles.header}>Shop Name</Text> <Text style = {styles.text}>{paramKey1}</Text> <View style={{ borderBottomColor: 'black', borderBottomWidth: StyleSheet.hairlineWidth, }} /> <View style = {styles.inputContainer}> <Text> Feedback: <Button onPress = {handlefb} title = "Post" buttonStyle={{ backgroundColor: 'black', borderWidth: 2, borderColor: 'white', borderRadius: 30, }} /></Text> <TextInput editable multiline numberOfLines={5} maxLength={500} placeholder = "Key in for any feedback for the shop" value = {todoDatafb} onChangeText ={text => setToDoDatafb(text)} style = {styles.input} /> <Text> Feedback by others:</Text> </View> </View> ) } export default Reviews
发布成功后,控制台日志显示todoDatafb为正确字符串(如"Awesome"),Firebase Storage控制台显示文件已存储,但下载后内容是一串数字而非预期字符串。参考YouTube教程,教程中存储的.txt文件正常显示文字。
更新:我在handlefb函数中添加日志:
const handlefb = async () => { const fb = sRef(storage, paramKey + `/${feedback + v1()}.txt`); console.log("Right before uploadString: " + todoDatafb) uploadString(fb, todoDatafb).then((snapshot) => { console.log('Uploaded new feedback') console.log("In uploadString: " + todoDatafb) }) }
日志显示上传前后todoDatafb均为正确字符串,请问为何下载文件显示数字?
解决方案
问题出在uploadString的默认行为:该方法默认会把传入的字符串当作base64编码处理,导致你的普通文本被错误编码,下载后解析成了字节数值。
只需在调用uploadString时,指定第三个参数为'raw',明确告知Firebase这是原始文本内容,不需要进行编码转换:
const handlefb = async () => { const fb = sRef(storage, paramKey + `/${feedback + v1()}.txt`); console.log("Right before uploadString: " + todoDatafb) // 添加第三个参数'raw' uploadString(fb, todoDatafb, 'raw').then((snapshot) => { console.log('Uploaded new feedback') console.log("In uploadString: " + todoDatafb) }) }
这样上传的文本会以原始字符串形式存储在Firebase Storage中,下载后就能正常显示预期的文字内容了。
内容的提问来源于stack exchange,提问作者L.Calvin
相关产品推荐
相关产品推荐

