如何使用base64数据下载文件

时间:2018-09-06 12:33:59

标签: jquery node.js

我正在开发将Node.js用作API的应用程序。在这里,我通过使用以下代码添加附件:

JQUERY: (在文件控件更改事件中)

  var reader = new FileReader();

                    // Closure to capture the file information.
                    reader.onload = (function (theFile) {
                        return function (e) {
                            saveAttachmentDraft(escape(theFile.name), e.target.result);
                        };
                    })(f);
                    // Read in the image file as a data URL.
                    reader.readAsDataURL(f);

function saveAttachmentDraft(name, src) {

var filename = name;
//var attachment = src;
var attachment = src.replace(/^data:image\/\w+;base64,/, '');
var type = name.substr((name.lastIndexOf('.') + 1));

    $.ajax({
        url: 'http://localhost:1400/api/workspace/PostAttachments',
        type: 'POST',
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        data: { 'lng_AttachmentId': 0, 'filename': filename, 'attachment': attachment, 'type': type },
        cache: false,
        success: function (data) {

            }
        },
        error: function (jqXHR, textStatus, err) {
            //show error message

        },
        beforeSend: function () {
            showProgress();

        },
        complete: function () {
            hideProgress();
        }
    });

}

NODE.JS:

router.route('/PostAttachments')
.post(function (req, res) {
var buffer = new Buffer(req.body.attachment, 'base64');
new sql.ConnectionPool(conn).connect().then(pool => {
    return pool.request()
        .input('lng_AttachmentId', sql.Int, req.body.lng_AttachmentId)
        .input('filename', sql.VarChar, req.body.filename)
        .input('attachment', sql.VarBinary(sql.MAX), buffer)
        .input('type', sql.VarChar, req.body.type)
        .execute("USP_InsertAttachments")
}).then(result => {
    let rows = result
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');
    res.status(200).json(rows);
    sql.close();
}).catch(err => {
    res.status(500).send({ message: "${err}", err })
    sql.close();
});
});

现在,当我尝试使用以下代码下载文件时,尝试打开下载的文件时出现了错误的数据错误:

JQUERY:

  $.ajax({
            url: 'http://localhost:1400/api/workspace/GetDownloadData',
            type: 'POST',
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',

            data: { 'lng_AttachmentId': obj.lng_AttachmentId },
            cache: false,
            success: function (data) {
                if (data.recordsets.length > 0) {
                    saveAsDownload(data.recordsets[0]);
                }
            },
            error: function (jqXHR, textStatus, err) {

            },
            beforeSend: function () {
                showProgress();

            },
            complete: function () {
                hideProgress();
            }
        });

function saveAsDownload (downloadedFile) {
// create a download anchor tag
var downloadLink = document.createElement('a');
downloadLink.target = '_blank';
downloadLink.download = downloadedFile[0].str_FileName;

// convert downloaded data to a Blob
var blob = new Blob([btoa(downloadedFile[0].str_FilePath.data)], { type: 'application/pdf' });
 //How i can replace 'application/pdf' for all type of files
//var blob = btoa(downloadedFile[0].str_FilePath.data);

// create an object URL from the Blob
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);

// set object URL as the anchor's href
downloadLink.href = downloadUrl;

// append the anchor to document body
document.body.append(downloadLink);

// fire a click event on the anchor
downloadLink.click();

// cleanup: remove element and revoke object URL
document.body.removeChild(downloadLink);
URL.revokeObjectURL(downloadUrl);

}

NODE.JS:

router.route('/GetDownloadData').post(function (req, res) {
new sql.ConnectionPool(conn).connect().then(pool => {
    // var sqlQuery = "USP_GetAttachmentToDownload";
    console.log(req.body.lng_AttachmentId);
    return pool.request()
        .input('lng_AttachmentId', sql.Int, req.body.lng_AttachmentId)
        .execute("USP_GetAttachmentToDownload")
}).then(result => {
    let rows = result;//result.recordset
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');
    res.status(200).json(rows);
    sql.close();
}).catch(err => {
    res.status(500).send({ message: "${err}", err })
    sql.close();
});
});

先谢谢了。 请让我知道是否需要更多信息,我会尽力提供更新。

0 个答案:

没有答案