如何将二进制文件发布到node.js

时间:2016-02-25 07:03:50

标签: javascript node.js

我是node.js和编码的新手,我试图将图片上传到node.js,我按照这个,将二进制文件上传到节点,由POSTMAN测试,但是当我选择body / POSTMAN中的二进制文件,URL类型http://localhost:3000/,是否带有api名称,节点始终回复

  

SyntaxError:意外的令牌�

我查了很多答案,尝试了6个小时,无法解决,请帮忙:(

节点app.js

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var multer  =  require('multer');
binary = require('binary');
var http = require('http');
app.use(bodyParser.json());
app.use(bodyParser.json({limit: '5mb'}));
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies.
songs = require('./routes/route');
var jsonParser = bodyParser.json();

app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
});
//////////////////
app.use(function(req, res, next) {
     var data = new Buffer('');
     req.on('data', function(chunk) {
         data = Buffer.concat([data, chunk]);
    });
    req.on('end', function() {
        req.rawBody = data;
        next();
    });
});
/////////////

app.get('/songs',songs.findAll);
app.get('/findById/:id',songs.findById);
app.post('/songs',songs.addSong);
app.put('/songs/:id',songs.updateSong);
app.delete('/songs/:id',songs.deleteSong);
app.post('/upload',songs.updateSong);
app.get('/upload/:file',songs.viewByFile);

route.js

var mongoose = require('mongoose');
var mongo = require('mongodb');
var uri = "mongodb://xxxx:xxxx@ds061365.mongolab.com:61365/aweitest";
mongoose.connect(uri);
var multer  =  require('multer');
// we're connected!
var db = mongoose.connection.db;
var BSON = require('bson').BSONPure;
var body = require('body-parser');
var fs = require('fs');

db.on('error', console.error.bind(console, 'connection errrrrrrrror:'));
//db = mongoose.connection.db;
db.once('open', function() {
    console.log("mongodb is connected!!");
});


exports.upload = function(req, res) {
    console.log(req.files.image.originalFilename);
    console.log(req.files.image.path);
    fs.readFile(req.files.image.path, function (err, data) {
        var dirname = "/Node/file-upload";
        var newPath = dirname + "/uploads/" +   req.files.image.originalFilename;
        fs.writeFile(newPath, data, function (err) {
            if (err) {
                res.json({'response':"Error"});
            } else {
                res.json({'response':"Saved"});
            }
        });
    });
};

exports.viewByFile = function (req, res){
  file = req.params.file;
     var dirname = "/Node/file-upload";
       var img = fs.readFileSync(dirname + "/uploads/" + file);
          res.writeHead(200, {'Content-Type': 'image/jpg' });
               res.end(img, 'binary');
  };

错误

 SyntaxError: Unexpected token �
 at parse (c:\Users\awei\node_modules\body-parser\lib\types\json.js:83:15)
 at c:\Users\awei\node_modules\body-parser\lib\read.js:116:18
 at invokeCallback (c:\Users\awei\node_modules\raw-body\index.js:262:16)
 at done (c:\Users\awei\node_modules\raw-body\index.js:251:7)
 at IncomingMessage.onEnd (c:\Users\awei\node_modules\raw- body\index.js:308:7)
 at emitNone (events.js:80:13)
 at IncomingMessage.emit (events.js:179:7)
 at endReadableNT (_stream_readable.js:906:12)
 at nextTickCallbackWith2Args (node.js:475:9)
 at process._tickCallback (node.js:389:17)

1 个答案:

答案 0 :(得分:1)

清除postman的缓存,然后尝试它或者只是在chrome中下载advance rest客户端的扩展并从那里测试