图像未通过nodeJs上传

时间:2016-03-09 12:49:39

标签: node.js

我正在从nodeJs上传图片。

控件未进入req.on('end')。在req.on('end')内没有打印任何内容。我无法确定问题出在哪里。我正在制作API并从js调用以在特定位置的服务器上传图像。

app.post('/tde/api/photo/:widgetId/:choosenFileName',function(req,res){
    console.log("In file Upload..");
    console.log(req.params.widgetId);
    console.log(req.params.choosenFileName);
    res.writeHead(200, { 'Content-Type': 'application/binary' });
    var filedata = '';
    var chunks = [];
    //req.setEncoding('binary');
    req.on('data', function(chunk){
        //filedata+= chunk;
        chunks.push(chunk);
    })
    req.on('end', function (chunk) {

            var dir = 'uploads/'+req.params.widgetId
            if (!fs.existsSync(dir)){
                fs.mkdirSync(dir);
                console.log("directory created..");
            }
            fs.readdir(dir, function(err, filenames) {
                if (err) {
                  onError(err);
                  return;
                }
                filenames.forEach(function(filename) {
                    console.log(filename);
                    fs.unlink(dir+'/'+filename, function(err) {
                        if (err) {
                            return console.error(err);
                        }
                        console.log("File deleted successfully!");
                    });
                });
                //fs.writeFile('uploads/'+req.params.widgetId+'/sanmoy.jpg', chunk,  function(err) {
                var fileName = req.params.choosenFileName;
                var widgetId = req.params.widgetId;
                    //fs.writeFile('uploads/'+widgetId+'/'+fileName, filedata, 'binary', function(err) {
                var buffer = Buffer.concat(chunks)
                fs.writeFile('uploads/'+widgetId+'/'+fileName, buffer, function(err) {
                    if (err) {
                        return console.error(err);
                    }
                    console.log("writing file success!");
                })  
            }); 

        });
    res.end("File is uploaded");
});

0 个答案:

没有答案