Using AngularJS and $http PUT method to send files in the request body

I am currently facing an issue with uploading files via an API call using the PUT method. After successfully uploading a file, I am encountering problems where the resulting file size is larger than expected and cannot be opened. For example, a 234 kb jpg file becomes 352 kb after upload, while a 12 kb docx file turns into 17 kb.

        var contentType = file.type;
        var reader = new FileReader();
        reader.onload = function (e) {
            var rawData = reader.result;

            $http({
                url: appSettings.serverPath + '/File/' + fileId + '/Content',
                method: 'PUT',
                headers: { 'Content-Type': undefined },
                data: rawData,
                transformRequest: []
            }).success(function (data, status, headers, config) {
                deferred.resolve(data);
            }).error(function (error) {
                deferred.reject(error);
            });

        };

        reader.readAsBinaryString(file);

Despite trying different content types in the header, the issue persists.

Attempted methods such as readAsArrayBuffer and readAsDataURL on a FileReader object did not solve the problem either. The former resulted in a file with 0 bytes, while the latter led to significantly larger file sizes that remained corrupted and inaccessible. Is there a specific encoding process or any other solution required to ensure accurate data transfer?

Any help would be greatly appreciated! Thank you.

Answer №1

Utilizing the FileReader API is unnecessary for reading files. The XHR Send Method automatically converts file objects into Blob objects.

    //var contentType = file.type;
    //var reader = new FileReader();
    //reader.onload = function (e) {
    //    var rawData = reader.result;

    return $http({
        url: appSettings.serverPath + '/File/' + fileId + '/Content',
        method: 'PUT',
        headers: { 'Content-Type': undefined },
        //data: rawData,
        data: file
        //transformRequest: []
    };
    /*  }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).error(function (error) {
            deferred.reject(error);
        });
    */

    //reader.readAsBinaryString(file);

Creating a promise using $q.defer is unnecessary as the $http service already provides a promise.

Additionally, the .success and .error methods have been deprecated and removed in Angular V1.6.


Deprecation of FileReader.readAsBinaryString()

The length of rawData matches the expected initial size based on the file size. However, uploaded files have additional bytes and cannot be opened correctly. For instance, a jpg file initially at 234 kb ends up being 352 kb post-upload, while a docx file starting at 12 kb increases to 17 kb after upload.

//reader.readAsBinaryString(file);

reader.readAsArrayBuffer(file)

The XHR Send Method transforms binary strings (DOMstring) to UTF-8. This encoding means that data bytes ranging from 128-255 are encoded with 2 bytes. Avoid converting binary data to DOMstrings; instead, utilize the ArrayBuffer API.

Deprecation of FileReader.readAsBinaryString()

Non-standard

This feature is non-standard and not part of any official standards track. Avoid using it on production sites accessible on the web, as it may not work for all users and can lead to significant inconsistencies between implementations with potential behavior changes in the future.

[It] was officially deprecated per the 12 July 2012 Working Draft from W3C.

— MDN Developer Reference - Web APIs - FileReader.readAsBinaryString()

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

Why isn't Freichat displaying the name of the user who logged in?

After creating my own small social networking site, I decided to add a chat script called freichat. However, I am facing an issue where when a user logs in, their name appears as "Guest102" instead of their actual name. I am quite confused by this problem ...

The usage of an import statement is not permissible outside of a module

Having some trouble using the mathjs library to calculate complex solutions for the quadratic equation. No matter how I try to import the library into my code, I keep encountering errors. Initially, I attempted this method: At the top of my root.js file, ...

Cors policy error encountered in Node.js application and React application

I have developed an application using Node.js and React. I am currently hosting the server side on node.kutiza.com and the client side on finanu.kutiza.com through Namecheap. However, when I try to make a request to node.kutiza.com, I encounter an error me ...

In order to use the serve command, it is necessary to run it within an Angular project. However, if a project definition cannot be located

An error occurred while running the ng serve command: C:\Mysystem\Programs\myfwms>ng serve The serve command needs to be executed within an Angular project, but a project definition could not be found. I encounter this error when ...

Error: Invalid character encountered during login script JSON parsing

I found this script online and have been experimenting with it. However, I encountered the following error: SyntaxError: JSON.parse: unexpected character [Break On This Error] var res = JSON.parse(result); The problem lies in the file below as I am unf ...

Invoke the onload event from document.ready using jQuery

Is it possible to trigger the onload event from within jQuery's document.ready function, such as in the example below: $(function() { onloadfunc(param); }); Comparison: <body onload = "onloadfunc(param);"> Do the above two methods achieve th ...

Having trouble with data retrieval from MySQL using PHP and Angular on certain mobile devices, although it functions properly on desktops and laptops

The data retrieved from the mysql database is functioning properly on desktop and laptop, but not on mobile devices. The following HTML code is present in the html file: <table class="table table-default"> <thead> <tr> & ...

d3: It appears that my routes are replicating themselves, and I am unable to ascertain the cause

I've been diving deep into D3, studying the works of Mike Bostock and other experts in the field. I'm also going through Scott Murray's book on Interactive Data Visualization specifically focusing on D3. At the moment, my project involves c ...

Update the state of the parent component based on changes made in the child component (both are functional

Here is the layout for the current issue: . ├── components │ ├── ModalPolicy.js │ ├── Footer │ ├── index.js ├── pages │ ├── index.js I attempted to display the Modal on Footer/index.js but it did no ...

Adding and removing dynamic fields with Bootstrap functionality

Recently, I've been trying to develop a feature where users can add and remove fields by clicking on a button. However, I've encountered a roadblock in my progress. If you take a look at this CodePen link, you'll see what I have so far. My a ...

What is the significance of the reserved keyword $scope in an AngularJS controller

I'm just starting out with Angular and recently stumbled upon this fiddle that illustrates how nested controllers work. I tried renaming $scope to $abc, but it didn't seem to work. Does this mean that $scope is a reserved keyword in AngularJS? f ...

What could be causing the abortTransaction() method in mongoose to not function as

System OS: MacOS 10.15.5 NodeJS Version: 10.16.3 Mongoose Versions: 5.8, 5.9 MongoDB Version: 4.0.3 The following code snippet is in question: import User from 'models/user' const session = await User.startSession() session.startTransaction() ...

Tips for assigning a JSON object as the resolve value and enabling autosuggestion when utilizing the promise function

Is there a way to make my promise function auto-suggest the resolved value if it's a JSON object, similar to how the axios NPM module does? Here is an example of how axios accomplishes this: axios.get("url.com") .then((res) => { Here, axios will ...

Centralizing images in a Facebook gallery/lightbox during the loading process

Is the image width and height stored in Facebook's gallery database? In typical JavaScript usage, the image width and height cannot be determined until the image is fully loaded. However, on Facebook, images are pre-loaded before being displayed, ens ...

Is there a way to switch the cursor to a pointer when hovering over a bar on a ChartJS bar graph?

Here's the chart I created: createChart = function (name, contributions, idArray) { globalIdArray = idArray; var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: "bar", data: { lab ...

Understanding the scope of variables in a JavaScript callback function

I am attempting to send an object variable to a callback function const sql = require('mssql'); const asset_update = function (connection, addr) { this.connection = connection; this.addr = addr; this.addr_long = parseInt(addr, 16); } ...

Unable to access property 'scrollToBottom' as it is undefined

I'm encountering the error "Cannot read property 'scrollToBottom' of undefined" and haven't been able to find a solution anywhere, hence this post: Here is my use case: I have a custom accordion list, and on click of one of the list i ...

Discover the method for storing multiple values in local storage using a dictionary with JavaScript

I have a scenario in my code where I need to update a value without storing a new one. Let's say I need to input values in the following format: { firstname:'kuldeep', lastname:- 'patel' } After entering the values, they g ...

Format the date using moment() for the last week of the current year and return it with the year. Next year's

I encountered an unusual problem when using Moment.js with Angular.js. When I use the .toISOString() method, I get the correct date, but when I use the .format() method, the date is completely wrong. Here is an example to illustrate the issue: Code snip ...

Is there a way to set the background image to scroll vertically in a looping pattern?

Is it possible to achieve this using only HTML5 and CSS3, or is JavaScript/jQuery necessary? ...