代码之家  ›  专栏  ›  技术社区  ›  billcane

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

  •  0
  • billcane  · 技术社区  · 10 年前

    我正在尝试上传一个文件,并用fontforge进行转换,然后将其发送回用户,这一切都非常可怕。 我的代码在我的第一台机器上运行,但后来我创建了一个Ubuntu Server VM,上面有Vagrant、SSHed、DLed fontforge、强大(基本上是nodejs),然后重试。 这就是我的 服务器.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 回复  |  直到 10 年前
        1
  •  0
  •   DrakaSAN    10 年前

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

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