繁体   English   中英

使用颤振将图像上传到 Firebase 失败

[英]Uploading images to Firebase with flutter fail

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM