将图像上传到带有颤动的Firebase失败



嗨,我正在使用flutter从设备摄像头或手机图库上传图像,并将其上传到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);
});
});

最新更新