Generate a binary string using JavaScript and then transform it into C#

I have an upload section in my JavaScript program. I utilize JS FileReader to obtain a binary string of the uploaded document before sending it to my C# WebApi for storage on the server.

JavaScript Code

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:

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

Although no errors occur during execution, attempting to open the file results in unrecognized content. Any suggestions on how to fix this issue?

Answer №1

Shoutout to @JeremyBenks for suggesting the use of a Base64 string instead. Here are the necessary modifications for my particular scenario:

JavaScript

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

Replace that with

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

C#

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

Swap it out for

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Capturing an active screen with Selenium in C# instead of the entire web page

Looking to capture a screenshot in my Automation Project. Wondering if there is a way to capture just the active screen visible on the browser rather than the entire web page. (Optional) Also, noticing low quality when saving the image in png format. Any ...

Is it possible to interpret the camera using radius or diameter instead of the traditional x, y, z coordinates

I've been exploring this scenario where I am trying to figure out if it is possible to move a camera by adjusting the radius and diameter instead of using x, y, z positions (Vectors). Currently, I am working with a cube, but my goal is to introduce a ...

Prisma: Utilizing the include option will retrieve exclusively the subobject fields

I created a function to filter the table building and optionally pass a Prisma.BuildingInclude object to return subobjects. async describeEntity(filter: Filter, include?: Prisma.BuildingInclude): Promise<CCResponse> { try { const entity = await ...

Navigate to a different directory within Cypress by utilizing the cy.exec() function

Dealing with cypress to execute a python script in another directory. However, it seems like the directory change is not functioning as expected. visitPythonProject() { cy.exec("cd /Users/**/Desktop/project/"); cy.exec("ls"); // thi ...

The module ~/assets/images/flags/undefined.png could not be found in the directory

When I use the img tag with a dynamic address filled using require, it works well in the component. However, when I try to write a test for it, an error is thrown. console.error Error: Configuration error: Could not locate module ~/assets/ima ...

Encountering an error when utilizing Firefox version 35 with protractor

When running my Angular app scenarios with Chrome, everything runs smoothly. However, I encounter a halt when trying to run the scenarios on Firefox version 35.0b6. Any help would be greatly appreciated. Thank you in advance. I am currently using Protract ...

Conditional Skipping of Lines in Node Line Reader: A Step-by-Step Guide

I am currently in the process of developing a project that involves using a line reader to input credit card numbers into a validator and identifier. If I input 10 numbers from four different credit card companies, I want to filter out the numbers from thr ...

Speeding up the loading time of my background images

body { background: url(http://leona-anderson.com/wp-content/uploads/2014/10/finalbackgroundMain.png) fixed; background-size:100% auto; } I have unique background images on each of my sites, but they are large in size and take some time to load due to bein ...

How to customize the arrow color of an expanded parent ExpansionPanel in material-ui

Currently facing a challenge in customizing material-ui themes to achieve the desired functionality. The goal is to have the expansion panels display a different arrow color when expanded for improved visibility. However, this customization should be appl ...

Add a new key-value pair to the mock data by clicking on it

Hey there! I'm currently tackling a task that involves toggling the value of a boolean and then appending a new key-value pair on click. I've been attempting to use the . operator to add the new key-value pair, but it keeps throwing an error. In ...

Having trouble launching the application in NX monorepo due to a reading error of undefined value (specifically trying to read 'projects')

In my NX monorepo, I had a project called grocery-shop that used nestjs as the backend API. Wanting to add a frontend, I introduced React to the project. However, after creating a new project within the monorepo using nx g @nrwl/react:app grocery-shop-weba ...

Error encountered on NodeJS server

Today marks my third day of delving into the world of Angular. I've come across a section that covers making ajax calls, but I've hit a roadblock where a tutorial instructed me to run server.js. I have successfully installed both nodejs and expre ...

Create random animations with the click of a button using Vue.js

I have three different lottie player json animation files - congratulations1.json, congratulations2.json and congratulations3.json. Each animation file is configured as follows: congratulations1: <lottie-player v-if="showPlayer1" ...

Utilizing JavaScript as the front-end client for a web application connected to the backend of

I am facing an interesting scenario with a coworker who has suggested using JavaScript in a Web client application (specifically EPiServer CMS) to manage all the documents in the backend (SharePoint Online). However, I am unable to figure out how to acce ...

Sorting JSON data in EJS based on categories

Hello, I am facing a dilemma. I need to apply category filtering to a JSON file but I am unsure of how to proceed with it. For instance, I wish to filter the 'vida' category along with its description and price. I seem to be stuck at this junctu ...

Adding Link Button Dynamically to ASP Grid ViewIncorporating Link Buttons into

I am working on implementing the following code in C# to include a link button in an asp:gridview. The output window displays that the text label has been added, indicating that the code ran successfully. However, upon loading the page, the link button is ...

Sorting arrays in JavaScript can become tricky when dealing with arrays that contain values from two different arrays

When working with two arrays in JavaScript that are received from PHP, I combine them into a single array. Each element in these arrays contains a created_at value (from Laravel), and I want to sort these elements by their created_at values. The issue ari ...

Dynamic mouse path

Currently, I am in the process of creating a mouse trail similar to what is found on this particular website. I have been using JavaScript, jQuery, and various libraries in my attempt to achieve this effect; however, it has proven to be more challenging th ...

Is there a way to switch up the dropdown chevron using only CSS after a click?

Is there a way to change the appearance of dropdown arrows using only CSS and animations when clicked on? I attempted the following method: body { background: #000; } #sec_opt select { /* Reset */ -webkit-appearance: none; -moz-appearance: n ...

Adding 7 days to a JavaScript date

Can you spot the bug in this script? I noticed that when I set my clock to 29/04/2011, it displays 36/4/2011 in the week input field! The correct date should actually be 6/5/2011 var d = new Date(); var curr_date = d.getDate(); var tomo_date = d.getDate( ...