【问题标题】:NodeJS HTTP POST receive an Image with ExpressNodeJS HTTP POST 通过 Express 接收图像
【发布时间】:2016-03-03 13:05:04
【问题描述】:

我正在使用 Bluemix 通过 NodeJS 开发一个“HTTP POST 侦听器”。该服务器应该是 Android 应用程序和 Watson Bluemix 服务之间的链接

这是我的代码

/*eslint-env node*/
// This application uses express as its web server
// for more info, see: http://expressjs.com
var express = require('express');

// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');

// create a new express server
var app = express();

// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));

// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();

/* 'BODY PARSER - NOT WORKING' */
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));

app.use(bodyParser.json());     //Assuming JSON  ENCODED INPUT
app.use(express.bodyParser({uploadDir:'/images'}));

// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {

// print a message when the server starts listening
console.log("server starting on " + appEnv.url);

app.post('/handle',function(request,response){
    var image64=request.body.encoded_String;
    var imageName=request.body.image_name;

    /*OK LOG THIS (Encoded Base64 image)*/
    console.log("IMG RECEIVED: " + imageName); //OK
    console.log("ENCODED: " + image64);        // = undefined (chunk problems?)

    response.writeHead(200, { "Content-Type": "text/plain" });
    response.write('Hello World - Example...\n');
    response.end(); 

    });

});

如何接收 base64 编码的图像并将其保存到文件夹中?

感谢您的帮助!

【问题讨论】:

  • 您没有告诉谁应该接收图像。也不是谁寄的。
  • console.log("IMG RECEIVED: " + imageName); //OK 所以这段代码接收到图像。这段代码是为 .... ?
  • 我应该通过 POST 接收图像 app.post('/handle',function(request,response){ var image64=request.body.encoded_String; var imageName=request.body.image_name; 但在 image64 中我只能在控制台日志中读取 undefined
  • 重复你的代码没有意义。即使你做了两次。最好提供更多信息。

标签: android node.js ibm-cloud ibm-mobile-services


【解决方案1】:

在 base64 中接收到的带有图像的字符串通常是在开头写入的格式,必须删除(或者至少我曾经删除它)。

var base64Data = str.replace(/^data:image\/png;base64,/, ""); // str - string with image

那你得用 fs 保存:

fs.writeFile("../dir/to/save/image.png", base64Data, 'base64', function(err) {});

基本上就这些了。

【讨论】:

  • 感谢您的帮助。在我能够保存这个图像之前我还有一个问题:如何保存以 base64 编码的字符串?当我收到一个 POST 时,我只能阅读 var imageName=request.body.image_name; 而在 image64=request.body.encoded_String; 我只能找到 undefined...
  • @Gian0508 这是前端问题。您应该根据向服务器发送 http 请求的框架来阅读文档。
猜你喜欢
  • 1970-01-01
  • 2021-10-01
  • 1970-01-01
  • 2016-07-09
  • 2018-08-03
  • 2013-03-12
  • 1970-01-01
  • 1970-01-01
  • 2012-11-14
相关资源
最近更新 更多