抖动将图像上传到Firebase失败

如何解决抖动将图像上传到Firebase失败

嗨,我正在使用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',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',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);
    });
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-