下载后NodeJS ZIP文件损坏

时间:2019-04-01 21:51:55

标签: node.js adm-zip

我开始使用Swagger-tools作为后端的nodejs项目。对于数据库,我使用Sequilize,而我正在使用AdmZip第三方库从文件路径生成zip文件,并将其作为响应发送给客户端。 问题是,当我从浏览器下载zip文件时,它说zip文件已损坏

这是我的代码:

module.exports.getFilesFromGroupZip = (req, res) => {

const options = swagger.convertParams(req, 'getFilesFromGroupZip');
var zip = new AdmZip("");

Groups.findOne({
    where: {
        id: options.id
    },
    include: {
        model: Files,
        through: {
            attributes: []
        }
    }
}).then(result => {
    result.files.forEach(file => {
        zip.addLocalFile(file.path);
    })
    response.sendZip(zip.toBuffer(), res, 200, 'getFilesFromGroupZip')

}).catch(err => {
    console.log(err)
    response.sendError(err, res, 404, 'getFilesFromGroupZip')
})
}

module.exports.sendZip = (result, response, statusCode, source) => {  

  response.statusCode = statusCode;
  response.setHeader('Content-Type', 'application/zip');  

console.log(`Returning ${response.statusCode} for ${source}`);

  response.end(result);
};

swagger.json:

   "/groups/{id}/zip.zip" : {
  "parameters": [
    {
      "name": "id",
      "in": "path",
      "required": true,
      "type": "string",
      "description": "groupID"
    }
  ],
  "get" : {
    "summary" : "Downloads zip file with files from selected group.",
    "description" : "Returns dataset zip.",
    "operationId" : "getFilesFromGroupZip",
    "produces": [  
      "application/gzip",
      "application/zip"
    ],
    "parameters" : [ ],
    "responses" : {
      "200" : {
        "description" : "Downloads zip file with files from selected group.",
        "schema" : {
          "type" : "file"
        }
      },
      "400" : {
        "$ref" : "#/responses/400"
      },
      "401" : {
        "$ref" : "#/responses/401"
      },
      "403" : {
        "$ref" : "#/responses/403"
      },
      "404" : {
        "$ref" : "#/responses/404"
      },
      "500" : {
        "$ref" : "#/responses/500"
      }
    },
    "x-swagger-router-controller" : "groupsController"
  }
},

0 个答案:

没有答案
相关问题