javascript - 在 C# 中将文件编码为 base64 并在 Node JS 中解码

标签 javascript c# node.js encoding

如何在 C# 中将 zip 文件编码为 base64 以及如何在 Node JS 中检索/解码它?

我使用下面的代码在 C# 中转换 base64

Byte[] bytes = File.ReadAllBytes("path of the file");
String file = HttpServerUtility.UrlTokenEncode(bytes);

我使用下面的代码来解码保存为 zip 文件的 Base64

var fs = require('fs');
var buf = new Buffer(fs.readFileSync('decoded.txt'), 'base64');
fs.writeFileSync('test.zip', buf);

但是当我尝试提取 zip 文件时。 zip 已损坏。

使用相同语言的 zip 文件执行编码/解码不会损坏。

我对此进行了研究。在 C# 中,字节数组先转换为 UTF-8,然后转换为 Base64。但我不知道谈话出了什么问题。

请指导我。特别是我对C#不太了解。

最佳答案

终于,我找到了解决问题的方法。它可能会对其他面临同样问题的人有所帮助。

1) 更改了@Srikanth 引用的 C# 编码

HttpServerUtility.UrlTokenEncode to System.Convert.ToBase64String(bytes); 

2) 我正在将 Base64 编码保存到 C# 中的文件中,并从 NodeJS 中读取它。问题是保存到文件时会添加附加字符,这会导致使用 NodeJS 解码时出现问题(总是获取损坏的 zip)UTF8 问题。

用于将 zip 文件转换为 Base64 编码的 C# 代码

using System;
using System.IO;
namespace email_zip
{
    public class Program
    {
        public static void Main(string[] args)
        {
             byte[] bytes = File.ReadAllBytes("./7738292858_January_February_2017.zip");
             string base64 = System.Convert.ToBase64String(bytes);
             Console.WriteLine(base64);
        }
    }
}

用于解码从 C# 项目接收的 base64 并提取 zip 文件的 NodeJS 代码

Decodes base64 string received from .NET project, Extract the zip file, and list all files included in decoded zip file (zipExtractor.js)

'use strict';
/**
 *  Decodes base64 string received from .NET project, Extract the zip file, and list all files included in decoded zip file
 */
var errSource = require('path').basename(__filename),
    fs = require('fs'),
    path = require('path'),
    async = require('async'),
    debug = require('debug')('cs:' + errSource),
    AdmZip = require('adm-zip'),
    mimeType = require('mime-types'),
    ZIP_EXTRACT_DIR = 'zip_extract'; // Default zip extract directory
// Check is zip extract directory exists / not. If not creates the directory 
var zipExtractorDir = path.join(__dirname, ZIP_EXTRACT_DIR);
if (!fs.existsSync(zipExtractorDir)) {
    fs.mkdirSync(zipExtractorDir);
}
/**
 * Callback for getting the decoded Base64 zip file
 *
 * @callback extractCallback
 * @param {Object} err If unable to decode Base64 and save zip file    
 * @param {Array<Object>} attachments Zip file extracted files
 */
/**
 * extract 
 * 
 * Decodes base64 string received from .NET project  
 * Covert to zip file
 * Extract the zip file and return all the mine-type and file data information 
 *  
 * @param {String} ticketInfo Base64 encoded string
 * @param {extractCallback} callback - A callback to decode and zip file extract
 */
function extract(ticketInfo /* Base64 encoded data */ , callback) {
    console.time('extract');
    async.waterfall([
        async.constant(ticketInfo),
        base64Decode,
        zipExtractor,
        deleteFile
    ], function(err, result) {
        console.timeEnd('extract');
        debug('extract', 'async.waterfall->err', err);
        debug('extract', 'async.waterfall->result', result);
        if (err) {
            // log.enterErrorLog('8000', errSource, 'extract', 'Failed to extract file', 'Error decode the base64 or zip file corrupted', err);
            return callback(err, null);
        }
        return callback(null, result);
    });
}
/**
 * Callback for getting the decoded Base64 zip file
 *
 * @callback base64DecodeCallback
 * @param {Object} err If unable to decode Base64 and save zip file    
 * @param {String} fileName Zip decode file name
 */
/**
 * Create file from base64 encoded string 
 * 
 * @param {String} ticketInfo Base64 encoded string
 * @param {base64DecodeCallback} callback - A callback to Base64 decoding
 */
function base64Decode(ticketInfo, callback) {
    var decodeFileName = 'decode_' + new Date().getTime() + '.zip', // Default decode file name
        base64DecodedString = new Buffer(ticketInfo, 'base64'); // Decodes Base64 encoded string received from.NET
    fs.writeFile(path.join(__dirname, ZIP_EXTRACT_DIR, decodeFileName), base64DecodedString, function(err) {
        if (err) {
            //log.enterErrorLog('8001', errSource, 'base64Decode', 'Failed to save the base64 decode zip file', '', err);
            return callback(err, null);
        }
        return callback(null, decodeFileName);
    });
}
/**
 * Callback for getting the decoded Base64 zip extracted file name.
 *
 * @callback zipExtractorCallback
 * @param {Object} err Unable to extract the zip file 
 * @param {String} fileName Zip decode file name's 
 */
/**
 * Extract zip file
 * 
 * @param {String} zipFile Decoded saved file
 * @param {zipExtractorCallback} callback - A callback to Base64 decoding
 */
function zipExtractor(zipFile, callback) {
    try {
        var zipFilePath = path.join(__dirname, ZIP_EXTRACT_DIR, zipFile),
            zip = new AdmZip(zipFilePath),
            zipEntries = zip.getEntries(); // An array of ZipEntry records 
        zip.extractAllTo( /*target path*/ ZIP_EXTRACT_DIR, /*overwrite*/ true);
        var zipFileAttachments = [];
        zipEntries.forEach(function(zipEntry) {
            if (!zipEntry.isDirectory) { // Determines whether the zipEntry is directory or not 
                var fileName = zipEntry.name, // Get of the file
                    filePath = path.join(__dirname, ZIP_EXTRACT_DIR, fileName),
                    attachment = {
                        filename: fileName,
                        path: filePath,
                        contentType: mimeType.contentType(path.extname(filePath))
                    };
                zipFileAttachments.push(attachment);
            }
            debug('zipExtractor->', 'attachment', attachment);
        });
        return callback(null, {
            name: zipFile,
            attachments: zipFileAttachments
        });
    } catch (err) {
        // log.enterErrorLog('8002', errSource, 'zipExtractor', 'Failed to extract file', 'Error decode the base64 or zip file corrupted', err);
        return callback(err, null);
    }
}
/**
 * Callback for getting the status of deleted decode file
 *
 * @callback deleteFileCallback
 * @param {Object} err Unable to delete the zip file 
 * @param {Array<Object>} attachment All zip file attachment Object
 */
/**
 * Delete decode zip file from the system
 * 
 * @param {String} zipFile Decoded saved file
 * @param {deleteFileCallback} callback - A callback to Base64 decoding
 */
function deleteFile(zipFileExtractInfo, callback) {
    var fileName = zipFileExtractInfo.name,
        filePath = path.join(__dirname, ZIP_EXTRACT_DIR, fileName);
    fs.unlink(filePath, function(err) {
        if (err && err.code == 'ENOENT') {
            //log.enterErrorLog('8003', errSource, 'deleteFile', 'Failed to delete decode zip file', fileName, err);
            debug('deleteFile', 'File doest exist, wont remove it.');
        } else if (err) {
            //log.enterErrorLog('8003', errSource, 'deleteFile', 'Failed to delete decode zip file', fileName, err);
            debug('deleteFile', 'Error occurred while trying to remove file');
        }
        return callback(null, zipFileExtractInfo.attachments);
    });
}

module.exports = {
    extract: extract
};

Executing C# program from NodeJS and reading Base64 console output. Decoding using zipExtractor.js.

var zipExtractor = require('./zipExtractor');
console.time('dotnet run');
var exec = require('child_process').exec;
// Follow instruction to set .NET in Mac OS https://www.microsoft.com/net/core#macos
exec('dotnet run', function(error, stdout, stderr) {
    console.timeEnd('dotnet run');
    if (error) {
        console.error(error);
        return;
    } else if (stderr) {
        console.error(stderr);
        return;
    }
    zipExtractor.extract(stdout, function(err, attachments) {
        if (err) {
            console.error(err);
        }
        console.info(attachments);
    });
});

输出:

dotnet run: 9738.777ms
extract: 155.196ms
[ { filename: '7738292858_January_February_2017.pdf',
    path: '/Users/andan/Documents/email_zip/zip_extract/7738292858_January_February_2017.pdf',
    contentType: 'application/pdf' } ]

关于javascript - 在 C# 中将文件编码为 base64 并在 Node JS 中解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43762287/

相关文章:

c# - 获取已填充 DataSource 的 ComboBox 的项目

C#:获取文件夹中的所有图像文件

linux - 如何安装 Cassandra nodejs

javascript - 使用 CryptoJS 在 Javascript 中加密并在 Java 中解密

javascript - ngRepeat 在另一个中继器值的数组上

javascript - 如何在单个语句中对 $$ ('selector' ) 数组使用 PrototypeJS .wrap() ?

c# - 为动态创建的 asp 面板设置内联样式

node.js - Letsencrypt 问题:请求消息格式错误::创建新的 authz::DNS 名称没有足够的标签时出错

node.js - 使用node-xbee发送数据包时出现校验和不匹配错误

javascript - Dropzone JS 在 ie9 中未通过验证