firebase - 使用颤振将图像上传到 Firebase 失败
问题描述
嗨,我正在使用颤振从设备相机或手机图库上传图像并将其上传到 Firebase 存储。我正在关注视频教程中的示例,但这些视频来自 2019 年或更早,可能代码或代码结构发生了一些变化。因此,为了部署 Firebase,我使用的是 node.js,它完美地部署了所有功能。当我尝试在调试控制台中上传时说上传失败。所以这是我得到的错误
D/EGL_emulation( 5628): eglMakeCurrent: 0xe1e853c0: ver 3 0 (tinfo 0xc8d7f240)
E/Surface ( 5628): getSlotFromBufferLocked: unknown buffer: 0x0
D/EGL_emulation( 5628): eglMakeCurrent: 0xe3ee0c80: ver 3 0 (tinfo 0xc8d7f0e0)
D/EGL_emulation( 5628): eglMakeCurrent: 0xe1e853c0: ver 3 0 (tinfo 0xc8d7f240)
D/EGL_emulation( 5628): eglMakeCurrent: 0xe3ee0c80: ver 3 0 (tinfo 0xc8d7f0e0)
D/eglCodecCommon( 5628): setVertexArrayObject: set vao to 0 (0) 13 0
D/skia ( 5628): Errors:
D/skia ( 5628):
D/skia ( 5628): Shader compilation error
D/skia ( 5628): ------------------------
D/skia ( 5628): Errors:
D/skia ( 5628):
D/skia ( 5628): Shader compilation error
D/skia ( 5628): ------------------------
D/skia ( 5628): Errors:
D/skia ( 5628):
I/flutter ( 5628): Something went wrong
I/flutter ( 5628): FormatException: Unexpected character (at character 1)
I/flutter ( 5628): Error: could not handle the request
I/flutter ( 5628): ^
I/flutter ( 5628): Upload failed!
D/skia ( 5628): Shader compilation error
D/skia ( 5628): ------------------------
D/skia ( 5628): Errors:
D/skia ( 5628):
W/mple.aplikacij( 5628): JNI critical lock held for 17.744ms on Thread[1,tid=5628,Runnable,Thread*=0xe8074000,peer=0x74f7eee0,"main"]
这是我在颤振中使用的方法
Future<Map<String, dynamic>> uploadImage(File image,
{String imagePath}) async {
final mimeTypeData = lookupMimeType(image.path).split('/');
final imageUploadRequest = http.MultipartRequest(
'POST',
Uri.parse(
'https://us-central1-flutter-aplikacija.cloudfunctions.net/storeImage'));
final file = await http.MultipartFile.fromPath(
'image',
image.path,
contentType: MediaType(
mimeTypeData[0],
mimeTypeData[1],
),
);
imageUploadRequest.files.add(file);
if (imagePath != null) {
imageUploadRequest.fields['imagePath'] = Uri.encodeComponent(imagePath);
}
imageUploadRequest.headers['Authorization'] =
'Bearer ${_authenticatedUser.token}';
try {
final streamedResponse = await imageUploadRequest.send();
final response = await http.Response.fromStream(streamedResponse);
if (response.statusCode != 200 && response.statusCode != 201) {
print('Something went wrong');
print(json.decode(response.body));
return null;
}
final responseData = json.decode(response.body);
return responseData;
} catch (error) {
print(error);
return null;
}
}
这是我在 Firebase 函数中得到的
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/Na8OD.png
And the Index.js the config for the firebase and deploy
const functions = require('firebase-functions');
const cors = require('cors')({ origin: true });
const Busboy = require('busboy');
const os = require('os');
const path = require('path');
const fs = require('fs');
const fbAdmin = require('firebase-admin');
const { v4: uuidv4 } = require('uuid');
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello from Firebase!");
// });
const { Storage } = require('@google-cloud/storage');
const storage = {
projectId: 'flutter-aplikacija ',
keyFilename: 'flutter-aplikacija.json'
};
fbAdmin.initializeApp({
credential: fbAdmin.credential.cert(require('./flutter-aplikacija.json'))
});
exports.storeImage = functions.https.onRequest((req, res) => {
return cors(req, res, () => {
if (req.method !== 'POST') {
return res.status(500).json({ message: 'Not allowed.' });
}
if (
!req.headers.authorization ||
!req.headers.authorization.startsWith('Bearer ')
) {
return res.status(401).json({ error: 'Unauthorized.' });
}
let idToken;
idToken = req.headers.authorization.split('Bearer ')[1];
const busboy = new Busboy({ headers: req.headers });
let uploadData;
let oldImagePath;
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
const filePath = path.join(os.tmpdir(), filename);
uploadData = { filePath: filePath, type: mimetype, name: filename };
file.pipe(fs.createWriteStream(filePath));
});
busboy.on('field', (fieldname, value) => {
oldImagePath = decodeURIComponent(value);
});
busboy.on('finish', () => {
const bucket = storage.bucket('flutter-aplikacija.appspot.com');
const id = uuidv4();
let imagePath = 'images/' + id + '-' + uploadData.name;
if (oldImagePath) {
imagePath = oldImagePath;
}
return fbAdmin
.auth()
.verifyIdToken(idToken)
.then(decodedToken => {
return bucket.upload(uploadData.filePath, {
uploadType: 'media',
destination: imagePath,
metadata: {
metadata: {
contentType: uploadData.type,
firebaseStorageDownloadTokens: id
}
}
});
})
.then(() => {
return res.status(201).json({
imageUrl:
'https://firebasestorage.googleapis.com/v0/b/' +
bucket.name +
'/o/' +
encodeURIComponent(imagePath) +
'?alt=media&token=' +
id,
imagePath: imagePath
});
})
.catch(error => {
return res.status(401).json({ error: 'Unauthorized!' });
});
});
return busboy.end(req.rawBody);
});
});
解决方案
问题出在 index.js 文件中,解决方案和编辑文件是
const functions = require('firebase-functions');
const cors = require('cors')({ origin: true });
const Busboy = require('busboy');
const os = require('os');
const path = require('path');
const fs = require('fs');
const fbAdmin = require('firebase-admin');
const { v4: uuidv4 } = require('uuid');
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello from Firebase!");
// });
const { Storage } = require('@google-cloud/storage');
const storage = new Storage({
projectId: 'flutter-aplikacija ',
keyFilename: 'flutter-aplikacija.json'
});
fbAdmin.initializeApp({
credential: fbAdmin.credential.cert(require('./flutter-aplikacija.json'))
});
exports.storeImage = functions.https.onRequest((req, res) => {
return cors(req, res, () => {
if (req.method !== 'POST') {
return res.status(500).json({ message: 'Not allowed.' });
}
if (
!req.headers.authorization ||
!req.headers.authorization.startsWith('Bearer ')
) {
return res.status(401).json({ error: 'Unauthorized.' });
}
let idToken;
idToken = req.headers.authorization.split('Bearer ')[1];
const busboy = new Busboy({ headers: req.headers });
let uploadData;
let oldImagePath;
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
const filePath = path.join(os.tmpdir(), filename);
uploadData = { filePath: filePath, type: mimetype, name: filename };
file.pipe(fs.createWriteStream(filePath));
});
busboy.on('field', (fieldname, value) => {
oldImagePath = decodeURIComponent(value);
});
busboy.on('finish', () => {
const bucket = storage.bucket('flutter-aplikacija.appspot.com');
const id = uuidv4();
let imagePath = 'images/' + id + '-' + uploadData.name;
if (oldImagePath) {
imagePath = oldImagePath;
}
return fbAdmin
.auth()
.verifyIdToken(idToken)
.then(decodedToken => {
return bucket.upload(uploadData.filePath, {
uploadType: 'media',
destination: imagePath,
metadata: {
metadata: {
contentType: uploadData.type,
firebaseStorageDownloadTokens: id
}
}
});
})
.then(() => {
return res.status(201).json({
imageUrl:
'https://firebasestorage.googleapis.com/v0/b/' +
bucket.name +
'/o/' +
encodeURIComponent(imagePath) +
'?alt=media&token=' +
id,
imagePath: imagePath
});
})
.catch(error => {
return res.status(401).json({ error: 'Unauthorized!' });
});
});
return busboy.end(req.rawBody);
});
});
推荐阅读
- kubernetes - kubernetes dashoboard「尝试访问服务时出错:'proxyconnect tcp: dial tcp:lookup $http_proxy: no such host」
- ios - 应用中收藏夹功能的最佳实践
- r - 嵌套列表到数据框 [使用 purrr + map]
- git - 如何在本地克隆整个 AOSP 代码库
- javascript - 如何使用 JS eventListener 更新 Firestore 数据库以提交表单
- c - 为什么 gcc 在 sizeof typedef'ed 指针上出错
- python - 返回数组中数字的总和,除了忽略以 6 开头并延伸到下一个 9 的数字部分。返回 0 表示没有数字
- node.js - 在 node.js 中使用云 sql 代理续集连接超时
- angular - Angular 中的异步/等待混淆代码 - 顺序错误
- django - 用于交叉多对多关系字段的 Django 查询集