Convert FileReader ArrayBuffer to Byte[] in order to transfer the data from a file

I have integrated a file upload feature into my web application, allowing users to upload images, .doc, .docx, and pdf files.

Currently, I am facing an issue with converting the file contents into a byte[] array to send it to my API for storage.

Although I attempted to convert from ArrayBuffer to Uint8Array, I encountered challenges and have not succeeded in resolving the issue.

Below is the snippet of code where I read the file and gather the necessary information:

Any assistance or guidance on this matter would be greatly appreciated.


let myFile = ev.target.files[0];
if(myFile.size > 0){
    let reader = new FileReader();
    var fileByteArray = [];
    reader.readAsArrayBuffer(myFile);
    reader.onloadend = (ev) => {                    
        var uintArray = new Uint8Array(reader.result.toString().length);
        //var arrayBuffer = new ArrayBuffer(reader.result);
        //var array = new Uint8Array(arrayBuffer);
        let resourceModel = new AddForumThreadResourceRequestModel({
            contentType: myFile.type,
            fileName: myFile.name,
            fileContent: uintArray
        });                   
        console.log(resourceModel);
        this.forumApi.AddThreadResource(resourceModel).subscribe(
            data => {
                if(data != null || data == true){
                    this.errorCtrl.presentToast("New resource has been added to the thread"); 
            }                                    
        });
    }   
}

Answer №1

Utilize the argument of the load event for improved functionality:

reader.onload = (e) => {                           
    var uintArray = new Uint8Array(reader.result);

    let resourceModel = new AddForumThreadResourceRequestModel({
        contentType: myFile.type,
        fileName: myFile.name,
        fileContent: uintArray
    });                    
    console.log(resourceModel);
    this.forumApi.AddThreadResource(resourceModel)
        .subscribe( data => {
            if(data != null || data == true){
                this.errorCtrl.presentToast("New resource has been added to the thread"); 
            }                                    
    });

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

Using JavaScript to transform base64 encoded strings into images

I'm currently working on an app using Titanium and I have a base64 string that I need to convert into an image from JSON data. Any assistance you can provide would be much appreciated. Thank you! ...

Filtering in JavaScript can be efficiently done by checking for multiple values and only including them if they are not

In my current coding challenge, I am attempting to create a filter that considers multiple values and only acts on them if they are not empty. Take the following example: jobsTracked = [ { "company": "Company1", ...

The issue arose in the Relay QueryRenderer fragmentContainer as it received conflicting IDs from the passed props and the server

Experiencing a curious problem: Initiating a graphql request from QueryRenderer Obtaining response data from server (verified through Network tab in dev tools) Props being populated in the QueryRenderer render({ error, props }) function The props are pas ...

Navigating a Facebook page login can have its challenges. Let's uncover the

Facebook now allows pages to be created without any associated Facebook users. These unowned pages are also able to sign into applications. How can an application identify and manage this scenario? Logout of Facebook Create a new Facebook page You have s ...

Include module A in module B, even though module A has already included module B's Angular

Currently, I am facing an issue with circular dependencies between two modules - User and Product. The User Module has already imported the Product Module to utilize the ProductListComponent. Now, I need to import/use the UserListComponent from the User Mo ...

The react component is not defined within the <Popup></Popup> tag

SOLVED: Big thanks to everyone who offered their assistance. Upon further investigation, I discovered that in the library I was using, the trigger={} functionality is specifically designed to work only with a button element. To address this issue, I took ...

Error in tabs.onUpdated argument in Firefox WebExtensions

I am currently working on developing a straightforward webExtension for Firefox and I would like to implement tabs.onUpdated with a filter. I found an example on the Mozilla website that I decided to use: const pattern1 = "https://developer.mozilla.org/*" ...

Parsing of the module failed due to an unexpected character appearing when trying to insert a TTF file into the stylesheet

As a newcomer to Angular, I recently completed the tutorial and am now working on my first app. While trying to add an OTF file, everything went smoothly. However, when I made a change to my app.component.css file and included this code snippet: @font-fa ...

When implementing jQuery AJAX, remember to properly encode script tags to prevent any

Looking for a way to avoid script tags in content loaded through AJAX? Check out this approach: $.ajax({ cache: false, type: 'GET', url: 'index.html', success: function(response) { $(response).find('<sc ...

Utilizing Angular 2 CLI's "ng build --prod" and "ng serve --prod" commands effectively while encountering 404 errors

After running ng build with the --prod option, my application compiles into a single main.js file without any errors in the console. However, when I attempt to run the application in the browser, it still searches for individual js files. This is evident ...

Where can the body of this function be located in Typescript and do the generics serve a practical purpose?

While perusing the documentation for Angular's "AsyncPipe", I found myself at a standstill on line 26, where the 'resolve' function is invoked: this.resolve !('hi there!'); I have some questions on my mind: (A) Where is the impl ...

Converting SASS in real-time using SystemJS

I have been reading various blogs discussing the use of SystemJS and SASS transpiling, but most of the examples I come across involve pre-processing SASS files before importing them into JavaScript code. However, I am interested in being able to directly i ...

Data from the server isn't loading in Angular2

I have successfully developed a basic Java app using REST that returns a string value when accessed through a REST client. However, I am now facing an issue in fetching the string value using an Http REST client in Angular2. I have set up a service to retr ...

What is preventing TypeScript from automatically inferring the type of an argument in a generic function that utilizes `keyof`?

What causes the error in this code snippet? type MyType = { a: string, b: string } function cantInfer<In, Out>(fn: (i: In) => Out, i: In) { } function myFunction<K extends keyof MyType>(key: K): string { return ''; } ...

Utilizing Angular RXJS to generate an array consisting of three different observable streams

I am trying to use three different streams to create an array of each one. For example: [homePage, mainNavigation, loan_originators] However, currently only mainNavigation is being returned. const homePage = this.flamelinkService.getData('homePage ...

Avoid the rendering of child elements in React

How can I skip rendering children in React? I want to enclose existing DOM nodes on a page within a React component. I need to render the frame only, excluding the static content which already exists as pre-existing DOM nodes. Is there a way to achieve t ...

capturing the null object in JavaScript

I am having trouble determining if the object is null or not an object. I tried using this line in an if condition to solve it, but it's not working. However, I keep getting an ERROR message stating "object is null or not an object". var preWynum = ...

Using Vue JS to set a default value in a custom radio group

Recently, I attempted to implement a default value in a custom radio component that I developed. Below is the code snippet: <template> <div class="custom-radio-button"> {{value}} <div v-for= "item in localValue"> <input type ...

The object function router(req, res, next) is encountering an error as it does not contain the required method for handling the request

I am trying to add a new row to my MySQL database, but I encountered an error message. Here is the scenario: I have set up Passport and hjs in my project. I am passing form data from app.js to a JavaScript file where I aim to insert the data. Object funct ...

Using JavaScript to assign the id attribute to the header element based on its content

Is there a straightforward way in JavaScript to assign an ID to a header based on its content, replacing spaces with hyphens and converting it to lowercase? Take, for instance, this header: <h1>Header one content</h1> How can we transform it ...