嗨,我正在使用flutter从设备相机或手机图库中上传图像,并将其上传至Firebase存储。我正在跟踪视频教程中的示例,但这些视频来自2019年或更早的版本,也许代码或代码结构有所变化。因此,要使用node.js部署Firebase I`m,它可以完美部署所有功能。当我尝试在调试控制台中上传时,提示上传失败。这是我得到的错误
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);
});
});
答案 0 :(得分:1)
问题出在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);
});
});