Read from input file using JavaScript and upload using XMLHttpRequest

Apologies for any language barriers. I am trying to upload my (.exe) file selected using an input file:

<input type="file" id="myfile">

Here is how it should be read in Javascript:

var myfile='';
var input = document.getElementById('myfile');
input.onchange = function(evt){
    var tgt = evt.target || window.event.srcElement, files = tgt.files;
    if (FileReader && files && files.length) {
            var fr = new FileReader();
            fr.onload = function(){
                myfile = fr.result;
            }
        fr.readAsDataURL(files[0]);
        }
}

Now, the variable "myfile" looks like this:

"data:application/msdownload;base64,0J/RgNC40LLQtdGCINC80LjRgCE= .... etc."

The base64 part contains the source file that was selected. However, when attempting to upload the file, its encoding and size change, resulting in corruption. What could I be doing wrong?

Here is the upload code being used:

    var fd = new FormData();
    var b = new Blob([atob(decodeURIComponent((myfile).split(',')[1]))],{type: 'application/msdownload'});
    fd.append('file', b, "myfile.exe");
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "http://myserver/");
    xhr.send(fd);

The file uploads successfully. However, upon downloading it again, the file ends up corrupted with changed encoding and size.

I have tried setting different headers like so:

xhr.setRequestHeader("Content-Type", "charset=windows-1251"); 
.............
xhr.setRequestHeader("Content-Type", "charset=utf-8");

But unfortunately, nothing seems to make a difference...

I am able to upload the file without AJAX, but I do need to retain the file locally and then upload it from a variable after manipulation.

In summary:

I have a Base64 encoded string like this:

0J/RgNC40LLQtdGCINC80LjRgCE=

I know this string represents the file "SecretFile.exe". I want to decode and upload this file using JavaScript. However, using standard window.atob to decode the string does not match the original file source. How can I properly decode this Base64 encoded file using FileReader?

Thank you.

Answer №1

There is no need to read the file into a data string and then convert it to a Blob. Any File object (such as one obtained from an

<input type="file" />
element) is inherently a Blob, so you can directly pass it to fd.append.

If manipulation of the File object is required before uploading, it would be best to utilize the FileReader's readAsArrayBuffer method instead. This method provides an ArrayBuffer which can be manipulated directly, followed by creating a blob using new Blob([ arrayBuffer ]) prior to uploading.

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

Is there a way to determine if an element has been scrolled past?

I am currently working on a script to detect when a specific element comes into view while scrolling. const targetElement = document.getElementById('sidebar'); window.addEventListener('scroll', () => { if (window.scrollY > tar ...

Changing ch to Px in CSS

Important Notes: I have exhaustively explored all the questions and answers related to this particular topic. The question I have is very straightforward: How many pixels are equivalent to 1 character? Here's a sample of my code - code Related Sear ...

The error message states that the object function defined as `(req, res, next) { app.handle(req, res, next); }` does not contain the method 'configure'

Could somebody help me understand why I encounter this error when attempting to execute the code below? var express = require('express'); var login = require('./routes/login'); var app = express(); //all configurations app.confi ...

What is the method for accessing the Redux store content directly in the console, without using any developer tools

By utilizing React Devtools, I am able to access the store by: $r.store.getState() Is there an alternate method to retrieve the store without using React Devtools? ...

Leverage the Power of JSON Data Manipulation in WordPress with Angular JS and the WordPress JSON

After testing code in this particular post and making some adjustments, I encountered an issue with obtaining a JSON object from the API of my blog created using the WordPress JSON plugin. URL of API from BLOG (NOT FUNCTIONING): URL from W3C example (WO ...

Execute with jQuery using Multiple Attribute Selector

I am attempting to input numeric values using a keyboard. My issue is as follows: the keyboard has an "Accept" button, and I have multiple text fields. I want to assign a different action for each text field. I attempted to use multiple attribute selector ...

ng-repeat not functioning properly with data defined in XMLHttpRequest

I have a problem with my HTML and AngularJS code. Initially, I defined the list in my controller which worked fine: <li ng-repeat="a in idmasVesselstableList"><a>{{a.table_name}}</a></li> And here is how I set up the controller: ...

Submit a set of form variables to PHP using AJAX

I am attempting to transmit a set of form parameters to a PHP script for processing. In the past, I have achieved this using $.post, but now my goal is to accomplish it exclusively with $.ajax. Below is the jQuery click event designed to send all variabl ...

Utilizing Pagination in Elasticsearch with MongoDB and ExpressJS

Despite my efforts to find a solution online, I have not yet come across anything that helps me achieve what I need. This is my first time working with ElasticSearch, and I am relatively new to Node.js and MongoDB as well. Following a tutorial, I impleme ...

Display alternative text dynamically

Trying to gain a deeper understanding of state in react, this is a perfect example to me. When I say dynamic, I mean displaying the output below instantly as it is entered in the form. class Demo extends Component { constructor(props) { super ...

Acquiring data within a jade template in order to generate static HTML pages

I am struggling to pass data to a jade template in order to generate static content. While I am not well-versed in node.js and express, I use jade as a template engine for creating static html. Many of the requests in the jade issue list pertain to includ ...

Utilizing Angular 2's *ngFor to conditionally wrap elements can be compared to organizing a layout with three columns in a Bootstrap row, then starting a

Currently I am facing a challenge with using *ngFor and it has me puzzled. My goal is to incorporate UIkit, but the same concept would apply to Bootstrap as well. <div *ngFor="let device of devices" > <div class="uk-child-width-expand@s uk-te ...

Creating a callback function within stored procedures using JavaScript Language Integrated Query in documentDB: A step-by-step guide

According to the documentation, the code snippets below are considered equivalent. However, I have observed that in the first case, I am able to perform operations on multiple documents within the callback function, whereas the map function in the latter s ...

What is the best way to send HTML content from a controller using ajax?

Here is the code in my controller: public async Task<ActionResult> GetHtml(int id) { var myModel = await db.Models.FindAsync(id); return Json(new { jsonData = myModel.MyHtml }, JsonRequestBehavior.AllowGet); } This is ...

Press the button to eliminate

Is there a way for users to add tags by typing text and then clicking on an add button? Once the tag is added, it appears with a delete button, allowing users to manage their list of tags. The JavaScript code below enables users to add tags successfully, ...

The functionality of the Bootstrap tabbed pane is not functioning correctly

I am currently in the process of creating a modal tabbed pane in bootstrap following the instructions provided in this guide. You can view the code and functionality on this fiddle. $(document).on("click","#tabs a",function(event) { alert("!!!"); ...

What is the best way to transfer information from an API to a state hook?

Encountering a recurring issue that requires some guidance. I am working on an API call and need to display the results in another component within the form's child elements. I've managed to create a component that can map state to JSX, but I&apo ...

Need assistance with implementing an Ajax feature for a sophisticated contact form submission?

Is there a way to run this contact form without needing to reload or change the page upon submission? I heard about using ajax for this purpose, but I'm not sure how to get started with that. I want the ability to show the message ('Successfully ...

``How does React facilitate the passing of properties from an API to a component?

I have two components - parentA and childB. I am trying to achieve a functionality where clicking a button in parentA triggers a function to fetch data from an API and then display it in the B component. On the surface, it seems like a simple task. Parent ...

How does ng-repeat determine the presence of duplicates within an array of objects?

angular.module("myApp",[]) .controller("myCtrl",function($scope) { $scope.persons = [{name:"teja",age:11}, {name:"Ash",age:12}, {name:"teja",age:11}]; }); In ...