简体   繁体   English

在Javascript中创建二进制字符串并在C#中转换

[英]Create binary string in Javascript and convert in C#

I have a file upload area in my JavaScript application.我的 JavaScript 应用程序中有一个文件上传区域。 When i upload the file i use JS FileReader to get a binary string of the uploaded file.当我上传文件时,我使用 JS FileReader 来获取上传文件的二进制字符串。 I then pass this to my C# WebApi and attempt to Write this to a file so that i can be stored on the server.然后我将它传递给我的 C# WebApi 并尝试将它写入一个文件,以便我可以存储在服务器上。

JS Code JS代码

let myFile = ev.target.files[0];
if(myFile.size > 0){
    let reader = new FileReader();
    var fileByteArray = [];
    reader.readAsArrayBuffer(myFile);
    reader.onloadend = (e) => {                     
        var buffer = <ArrayBuffer>reader.result;
        var uintArray = new Uint8Array(buffer);
        var binaryString = String.fromCharCode.apply(null, uintArray);

        let resourceModel = new Model({
            contentType: myFile.type,                            
            fileName: myFile.name,
            fileContent: binaryString
         });                   

    } 
}

C# Code: C# 代码:

if (!String.IsNullOrEmpty(model.fileContent))
{
    byte[] bytes = Encoding.UTF8.GetBytes(model.FileContent);
    File.WriteAllBytes(RESOURCES_SAVE_PATH, bytes);                
}

It all looks like it works, there are no errors thrown during execution.看起来一切正常,在执行过程中没有抛出任何错误。 However, when you go to open the file, the file wont open as it doesnt recognise the contents.但是,当您打开该文件时,该文件无法打开,因为它无法识别内容。

Any ideas how i can get this working?我有什么想法可以让这个工作吗?

Thanks to @JeremyBenks for the idea of using a Base64 string instead.感谢 @JeremyBenks 提出使用 Base64 字符串的想法。 The relevant changes for my example are as follows:我的示例的相关更改如下:

JS JS

var binaryString = String.fromCharCode.apply(null, uintArray);

For this为了这

var b64String = btoa(String.fromCharCode.apply(null,uintArray));

C# C#

byte[] bytes = Encoding.UTF8.GetBytes(model.FileContent);

For this为了这

byte[] bytes = Convert.FromBase64String(model.FileContent);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM