如何使用archiver nodejs expressjs在ajax请求中下载Zip文件

时间:2017-02-26 23:24:51

标签: jquery ajax node.js express archiverjs

ExpressJS

app.post('/api/v1/imagelist_data/image-data/', function(req, res) {
console.log("I received a NEW POST request");


res.set('Content-Type', 'application/zip');
res.set('Content-Disposition', 'attachment; filename=myFile.zip');

var zip = Archiver('zip');

// Send the file to the page output.
zip.pipe(res);

// Create zip with some files. Two dynamic, one static. Put #2 in a sub folder.
zip.append('Some text to go in file 1.', {
        name: '1.txt'
    })
    .append('Some text to go in file 2. I go in a folder!', {
        name: '2.txt'
    });

zip.finalize();

});

使用jQuery的客户端代码

$('#Image_form').on('submit', function(e) {
//Getting the Collection Name from Form
var frm_data = $('#myForm').serializeArray();
var DBValue = frm_data[0].value;


var url = "http://localhost:3000/api/v1/imagelist_data/image-data/" + DBValue;
var formData = $('#Raw_form').serializeArray();

$.ajax({
    type: "POST",
    url: url,
    data: formData,
    success: function(data, status, headers, config) {
        // useReturnData(data);
        var file = new Blob([data], {
            type: 'application/zip'
        });
        window.location = URL.createObjectURL(file);

    }
   });
});

Ajax请求 Request

Ajax响应 Response

我无法使用ExpressJS下载由我的Nodejs服务器创建的Zip文件。

在客户端按钮点击事件我正在使用带表单数据的Ajax请求并将响应数据作为下载文件返回。我怎么能用这种方法在客户端使用Ajax下载zip文件。

或者如果Ajax dunt触发下载文件,我应该在客户端使用什么来下载文件。并建议我是否需要在服务器端进行一些更改

0 个答案:

没有答案