草庐IT

javascript - 如何使用 javascript 中的 http.post 将图像发送到服务器并在 mongodb 中存储 base64

coder 2025-02-12 原文

我在使用 mongodb 在服务器端存储图像的客户端访问 http 请求时遇到了问题。我非常感谢帮助。我需要一个简单的示例来说明如何将图像文件作为数据添加到 http post 请求(例如 XMLhttprequest)中。比方说,我知道服务器方法的网址。图片来源定义在

imgsrc

文件名存放在

name

我有这个自动取款机:

var http = new XMLHttpRequest();
httpPost.onreadystatechange = function(err) {
        if (httpPost.readyState == 4 && httpPost.status == 200){
            console.log(httpPost.responseText);
        } else {
            console.log(err);
        }
    }
var  path = "http://127.0.0.1:8000/uploadImage/"+name;
httpPost.open("POST", path, true);
// I guess I have to add the imagedata into the httpPost here, but i dont know how
httpPost.send(null);

然后在服务器端的路径上,将调用以下方法,我想将 base64 编码图像的 url 存储在 mongodb 中。如何从 httpPost 访问图像?

function postNewImageType(req, res, next){
    var newImageTypeData = {
         name: req.params.name,
         image: "placeholder.png"
    }
    var data = // how to access the image?
    var imageBuffer = decodeBase64Image(data);
    fs.writeFile(cfg.imageFolger+newImageTypeData._id+'.jpeg', imageBuffer.data, function(err){
        if (err) return new Error(err);
        newImageTypeData.set({image:newImageTypeData._id+'.jpeg'});
        var image = new ImageType(newImageData);

    });
    imagetype.save(function (err) {
        if (error) {return next(new restify.InvalidArgumentError(JSON.stringify(error.errors)));}
        else { res.send(201, imagetype);}
    });   
}

最佳答案

您可以通过多种方式将请求中的图像数据发送到服务器,但所有这些方式都涉及使用您希望发送的数据调用 XMLHttpRequest 对象的 send 方法发送作为它的参数。

send 方法将请求分派(dispatch)到远程服务器,并将其参数设置为该请求的主体。由于您希望服务器上有 Base64 编码的图像数据,因此您首先需要在客户端将图像文件转换为 Base64 数据。

在客户端将图像转换为 Base64 的最简单方法是将图像作为图像元素加载,将其绘制到 Canvas 元素,然后获取 Canvas 图像数据的 Base64 表示形式。

这可能类似于以下内容(假设原始图像的 URL 存储在名为 imgsrc 的变量中,并且所需名称存储在 name 中,如下所示)说明):

// This function accepts three arguments, the URL of the image to be 
// converted, the mime type of the Base64 image to be output, and a 
// callback function that will be called with the data URL as its argument 
// once processing is complete

var convertToBase64 = function(url, imagetype, callback){

    var img = document.createElement('IMG'),
        canvas = document.createElement('CANVAS'),
        ctx = canvas.getContext('2d'),
        data = '';

    // Set the crossOrigin property of the image element to 'Anonymous',
    // allowing us to load images from other domains so long as that domain 
    // has cross-origin headers properly set

    img.crossOrigin = 'Anonymous'

    // Because image loading is asynchronous, we define an event listening function that will be called when the image has been loaded
    img.onLoad = function(){
        // When the image is loaded, this function is called with the image object as its context or 'this' value
        canvas.height = this.height;
        canvas.width = this.width;
        ctx.drawImage(this, 0, 0);
        data = canvas.toDataURL(imagetype);
        callback(data);
    };

    // We set the source of the image tag to start loading its data. We define 
    // the event listener first, so that if the image has already been loaded 
    // on the page or is cached the event listener will still fire

    img.src = url;
};

// Here we define the function that will send the request to the server. 
// It will accept the image name, and the base64 data as arguments

var sendBase64ToServer = function(name, base64){
    var httpPost = new XMLHttpRequest(),
        path = "http://127.0.0.1:8000/uploadImage/" + name,
        data = JSON.stringify({image: base64});
    httpPost.onreadystatechange = function(err) {
            if (httpPost.readyState == 4 && httpPost.status == 200){
                console.log(httpPost.responseText);
            } else {
                console.log(err);
            }
        };
    // Set the content type of the request to json since that's what's being sent
    httpPost.setHeader('Content-Type', 'application/json');
    httpPost.open("POST", path, true);
    httpPost.send(data);
};

// This wrapper function will accept the name of the image, the url, and the 
// image type and perform the request

var uploadImage = function(src, name, type){
    convertToBase64(src, type, function(data){
        sendBase64ToServer(name, data);
    });
};

// Call the function with the provided values. The mime type could also be png
// or webp

uploadImage(imgsrc, name, 'image/jpeg')

当您的服务器收到请求时,请求正文将包含 JSON 字符串,其中包含您的 Base64 图像。由于您没有提供用于 Mongo 的服务器框架或数据库驱动程序,我已经调整了您的代码,假设您使用的是 Express 和 Mongoose 以及应用程序中已经定义的 ImageType 模型。

由于您始终可以从其 _id 属性和您的图像文件夹路径构造图像记录的文件名,因此将其保存为记录的属性不一定有意义,但是我在这里保留了该功能,这将要求您在一个请求周期内保存记录两次。

我还更改了处理文件系统调用错误的方式。从文件系统错误中返回的 'err' 已经是一个 Error 对象,需要由您的服务器以某种方式处理。

function postNewImageType(req, res, next){
    var json = JSON.parse(req.body),
        newImageTypeData = {
            name: json.name,
            image: "placeholder.png"
        },
        imageBuffer = decodeBase64Image(data),
        newImageType = new ImageType(newImageTypeData);

    //First we save the image to Mongo to get an id

    newImageType.save(function(err){
        if(err) return next(new restify.InvalidArgumentError(JSON.stringify(err.errors)));
        var fileName = cfg.imageFolder + newImageType._id + '.jpeg';

        fs.writeFile(fileName, imageBuffer.data, function(err){
            //Handle error in next middleware function somehow
            if (err) return next(err);
            newImageType.set({image: 'filename.png'});
            newImageType.save(function(err){
                if (err) return next(new restify.InvalidArgumentError(JSON.stringify(err.errors)));
                res.send(201, imagetype);
            });
        })
    });
}

关于javascript - 如何使用 javascript 中的 http.post 将图像发送到服务器并在 mongodb 中存储 base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34972072/

有关javascript - 如何使用 javascript 中的 http.post 将图像发送到服务器并在 mongodb 中存储 base64的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  4. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  5. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  6. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  7. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  8. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  9. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  10. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

随机推荐