嘿,我尝试将用户上传的图片存储在Firebase存储中。
但是我不知道如何访问文件,因为当我用AJAX发送图片时,我在Node中收到的消息是:blob:http://localhost:3000/f64a37b5-ec9f-4b99-8784-0fe7842e22da。
当我尝试发送它时,它不起作用。
我将代码放在下面:
反应部件->
uploadPicture(file) {
const data = new FormData();
data.append('file', this.uploadInput.files[0]);
data.append('filename', this.fileName.value);
console.log(file[0])
fetch('/upload_picture', {
method: 'post',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({
"picture": file[0]
})
})
}
console.log(file [0])使我感到:
File(330479)
{preview: "blob:http://localhost:3000/c128fe5d-db61-4caa-8851-95e397b67e6a", name: "Capture d’écran 2018-07-27 à 11.34.01.png", lastModified: 1532684046000, lastModifiedDate: Fri Jul 27 2018 11:34:06 GMT+0200 (heure d’été d’Europe centrale), webkitRelativePath: "", …}
lastModified: 1532684046000
lastModifiedDate: Fri Jul 27 2018 11:34:06 GMT+0200 (heure d’été d’Europe centrale) {}
name: "Capture d’écran 2018-07-27 à 11.34.01.png"
preview: "blob:http://localhost:3000/c128fe5d-db61-4caa-8851-95e397b67e6a"
size: 330479
type: "image/png"
webkitRelativePath: ""
__proto__: File
快递->
const express = require('express')
const router = express.Router()
const firebase = require('firebase')
const googleStorage = require('@google-cloud/storage')
const storage = googleStorage({
projectId: "-------ha",
keyFilename: "-------------------------WTY"
})
const bucket = storage.bucket("gs://------ha.appspot.com")
router.post('/upload_picture', (req, res) => {
const file = req.body.picture.preview
console.log(file)
bucket.upload(file, function(err, file) {
if (!err) {
console.log(`${file} add to firebase`)
}
else
console.log('Error')
});
})
console.log(file)渲染了我:blob:http://localhost:3000/f64a27b5-ec9f-4b99-8784-0fe7842e22da
当我上传文件时,这使我出现“错误”。
有人知道怎么了吗?
答案 0 :(得分:0)
我建议您使用Firebase JavaScript SDK,以便您可以将图像直接从React前端直接上传到云存储,而不必将图像传递到节点服务器(https://firebase.google.com/docs/storage/web/start)。首先将Firebase安装到您的react项目中。
npm install --save firebase
然后使用适当的设置配置Firebase并直接从react上传。
import * as firebase from 'firebase';
var config = {
apiKey: '<your-api-key>',
authDomain: '<your-auth-domain>',
databaseURL: '<your-database-url>',
storageBucket: '<your-storage-bucket>'
};
firebase.initializeApp(config);
// Get a reference to the storage service, which is used to create references in your storage bucket
var storage = firebase.storage();
// Create a root reference
var storageRef = firebase.storage().ref();
// Create a reference to 'mountains.jpg'
var exampleRef = storageRef.child('example.jpg');
var file = ... // use the Blob or File
exampleRef.put(file).then(function(snapshot) {
console.log('Uploaded a blob or file!');
});