将文件编码到C#中的base64和Node JS中的Decode

时间:2017-05-03 14:02:03

标签: 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);

我使用下面的代码解码base64另存为zip文件

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 个答案:

答案 0 :(得分:0)

最后,我找到了解决问题的方法。它可能有助于其他人如何面对同样的问题。

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代码

  

解码从.NET项目收到的base64字符串,解压缩zip   文件,并列出解码的zip文件中包含的所有文件   (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
};
  

从NodeJS执行C#程序并读取Base64控制台输出。   使用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' } ]