使用NodeJS和Swagger将文件上传到服务器

时间:2019-03-06 10:24:31

标签: javascript node.js swagger

我想使用Swagger将文件上传到服务器。我创建了YAML来上传文件,如下所示:

/Upload:
post:
  summary: Uploads a file.
  operationId: bulkUpload
  consumes:
    - multipart/form-data
  parameters:
    - in: formData
      name: upfile
      type: file
      description: The file to upload.   
  responses:
    200:
      description: "File Uploaded"
  x-swagger-router-controller: "Default"

我的DefaultService.js文件包含该功能:

var fs = require('fs');

exports.bulkUpload = function(args, res, next)
{
  var stream = fs.createWriteStream("UploadedFile.txt");
  stream.once('open', function ()
  {
    stream.write('blah blah');                      //works - writes 'blah blah' to file
    stream.write(JSON.stringify(args.upfile.value));//bombs out after a while    
    stream.write(args.upfile);                      //does not work
    stream.write(args.upfile.value);                //does not work
    stream.end();
  });

  res.setHeader('Content-Type', 'application/json');
  res.statusCode = 200;
  res.end(JSON.stringify('File Uploaded'));
}

您将看到我正在尝试将上传的文件写入测试文件“ UploadedFile.txt”。从我的尝试中可以看出,它当前正在失败。

我想上传原始文件而不必创建自己的测试文件。我该怎么办?

0 个答案:

没有答案