【问题标题】:Uploading image to google drive without file input field在没有文件输入字段的情况下将图像上传到谷歌驱动器
【发布时间】:2023-01-19 02:40:46
【问题描述】:

在通过图像裁剪库裁剪图像后,我需要通过 nodejs 将图像上传到谷歌驱动器。以前我是用文件输入字段上传图像,所以我可以在后端(nodejs)中获取图像的缓冲区(使用 express-fileupload 库)。现在的问题是,裁剪后我的图像形式为

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAA....

如何以这种形式将图像发送到后端,以便我们可以获得该图像的缓冲区,以便上传到谷歌驱动器。否则我们可以直接将其上传到前端的谷歌驱动器(javascript)吗? .我尝试使用 FormData 但我只能得到字符串而不是缓冲区。

【问题讨论】:

  • 是的,这应该是可能的。你试过什么了?你卡在哪儿了?
  • 我尝试像在后端 NodeJs 中一样将图像 URL 转换为缓冲区并上传到驱动器。但我不能也不知道天气会起作用。我想知道我可以将天气作为文本文件上传,但它看起来很傻。即使我尝试手动将图像分配给文件输入字段,也知道这是不可能的。请有任何选择。
  • 我尝试使用表单数据并且它有效。但是在后端我没有得到提交图像的缓冲区,而是得到类似' ------WebKitFormBoundaryrdxcaeywmG7EOWuK\r\nContent-Disposition: form-data; name': '"magei"\r\n' + '\r\n' + 'data:image/png;base64,iVBORw0KGgoAAAA......'.. 如何像普通表单数据一样解析它。
  • 请通过编辑为您的问题添加所有说明。不要忘记分享您正在使用的代码

标签: javascript node.js image google-drive-api


【解决方案1】:
  • 这取决于您的后端和前端是如何连接的,因为您将无法使用这种形式将图像传输到后端HTTP POST作为一个的最大尺寸HTTP POST64KB
  • 但是,很有可能使用 blob 形式将图像发送到后端WebSocket/WebRTC喜欢图书馆套接字.io
  • 例如让我们使用一个 express 后端和一个带有一些 javascript 的传统静态 html 主页例子
    //my webpage which has the blob this is some browser javascript connected to a html file
    //Hosted on http://localhost:3000
          var base64data
    //I have a cake.png in my static directory
            fetch("cake.png")
                .then(response => response.blob())
                .then(blob => {
                    const fileReader = new FileReader();
                    fileReader.readAsDataURL(blob);
                    fileReader.onloadend = function() {
                        base64data = fileReader.result;
                    }
                })
            .catch(error => {
                console.error(error);
            });
          const socket = io("http://localhost:4000")
            socket.on('connect',()=>{
    //Sent this blob to the server
              socket.emit('blob',base64data)
            }) 

我的 nodejs 文件有一个 socket.io 和驱动 api Socket.io 服务器托管在 http://localhost:4000


const { Server } = require("socket.io");
const google = require("googleapis");
const io = new Server(4000, {
    cors: {
        "Access-Control-Allow-Origin": "*",
        methods: ["GET", "POST", "OPTIONS"],
    },
});
/*Initialize the drive
 *......
 *......
 */
io.on("connection", (socket) => {
    socket.on("blob", (blob) => {
        drive.files.create({
            requestBody: {
                name: "image.png",
                mimeType: "image/png",
            },
            media: {
                mimeType: "image/png",
                body: blob,
            },
        });
    });
});

因此,blob 可以用作身体创建文件时

【讨论】:

    猜你喜欢
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 2019-11-10
    • 2019-08-04
    • 1970-01-01
    相关资源
    最近更新 更多