使用Nodejs上传:使用response.end发送错误文件

时间:2014-07-21 10:48:40

标签: node.js vagrant ubuntu-server formidable fontforge

我正在尝试上传文件并使用fontforge进行转换,然后将其发送给用户,所有这些都是强大的。 我的代码在我的第一台机器上运行,但后来我创建了一个Uagntu-Server虚拟机,其中包含Vagrant,SSHed,DLed fontforge,强大(基本上是nodejs),并重试。 这就是我的 server.js 文件的样子:

var formidable = require('formidable'),
http = require('http'),
exec = require("child_process").exec,
fs = require("fs");


http.createServer(function(req, res) {

    var form = new formidable.IncomingForm();

    form.parse(req, function(err, fields, files) {
    console.log(files);
    console.log(fields);
    exec("fontforge -script convert.sh -format \"." + fields.format + "\"" + " " + files.upload.path, function(error, stdout, stderr) {
        if (error !== null) {
          console.log('exec error: ' + error);
        }
        res.setHeader('Content-disposition', 'attachment; filename=' + files.upload.name.replace('svg', fields.format));
        res.writeHead(200, {'Content-Type': 'application/x-font-' + fields.format});
        res.end(files.upload.path + "." + fields.format);
        fs.unlink(files.upload.path, function (err) {
          if (err) throw err;
          console.log('successfully deleted ' + files.upload.path);
        });
        fs.unlink(files.upload.path + "." + fields.format, function (err) {
          if (err) throw err;
          console.log('successfully deleted ' + files.upload.path + "." + fields.format);
        });

      });
    });

    return;
}).listen(8080);

表单在客户端上显示正确(一些带有post方法的基本index.html页面),但是给我发回一个31字节的文件(而不是6.1k),具有正确的名称和扩展名,但绝对不是正确的内容。

控制台日志显示:

{ upload:
   { domain: null,
    _events: {},
     _maxListeners: 10,
 size: 29526,
 path: '/tmp/bcb357fa7f8e5fcc075964c6bcbbe9bb',
 name: 'hamburg.svg',
 type: 'image/svg+xml',
 hash: null,
 lastModifiedDate: Mon Jul 21 2014 11:04:00 GMT+0000 (UTC),
 _writeStream:
  { _writableState: [Object],
    writable: true,
    domain: null,
    _events: {},
    _maxListeners: 10,
    path: '/tmp/bcb357fa7f8e5fcc075964c6bcbbe9bb',
    fd: null,
    flags: 'w',
    mode: 438,
    start: undefined,
    pos: undefined,
    bytesWritten: 29526,
    closed: true } }     }

{ format: 'ttf' }

1 个答案:

答案 0 :(得分:0)

您的问题是您正在将路径发送到转换后的文件。要发送文件本身,您需要使用:

fs.readFile(files.upload.path + '.' + fields.format, function (err, data) {
    if (err) {
        res.end('Error: ' + err);
    } else {
        res.end(data);
    }
});
相关问题