Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/447.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在C#中将文件编码到base64,并在Node JS中解码_Javascript_C#_Node.js_Encoding - Fatal编程技术网

Javascript 在C#中将文件编码到base64,并在Node JS中解码

Javascript 在C#中将文件编码到base64,并在Node JS中解码,javascript,c#,node.js,encoding,Javascript,C#,Node.js,Encoding,如何在C#中将zip文件编码为base64,以及如何检索/解码它 我使用下面的代码在C中转换base64# 我使用了下面的代码来解码base64另存为zip文件 var fs = require('fs'); var buf = new Buffer(fs.readFileSync('decoded.txt'), 'base64'); fs.writeFileSync('test.zip', buf); 但是当我试图解压缩zip文件时。zip正在被破坏 使用相同语言的zip文件执行编码/解码不

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

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

我使用了下面的代码来解码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) 更改了@Srikanth引用的C#编码

HttpServerUtility.UrlTokenEncode to System.Convert.ToBase64String(bytes); 
2) 我正在用C#将base64编码保存到文件中,并从NodeJS读取它。问题是保存到文件时添加了额外的字符,这使得使用NodeJS(始终获取损坏的zip)UTF8对其进行解码时出现问题

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

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);
        }
    }
}
NodeJS代码,用于解码从C#project接收的base64并提取zip文件

解码从.NET项目接收的base64字符串,提取zip 文件,并列出解码zip文件中包含的所有文件 (zipExtractor.js)

输出:

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' } ]
这个答案解释了从utf-8到code64的转换。试着做相反的事情;)
'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
};
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' } ]