Transforming a Blob document into JSON format

I am attempting to convert a blob file into JSON format in order to transmit it via AJAX requests. Despite my efforts with the code below, I have not been successful in achieving this task. When I attempt to parse the JSONified file, I end up with a completely different file that is much smaller in size.

function convertBlobToJSON(blob, callback) {

        var fileReader = new FileReader()
        fileReader.readAsArrayBuffer(blob)
        fileReader.onloadend = function() {             

            // Client-side
            var array = Array.from(new Uint8Array(fileReader.result))
            var data = {data: array }
            var json = JSON.stringify(data)

            // Server-side
            var parsedData = JSON.parse(json)
            var byteArray = parsedData.data.buffer
            var blobData = new Blob([byteArray])
       }        
}

Answer №1

To efficiently transfer data from client to server, consider using the FileReader.readAsDataURL() method to send data as a base64 encoded string. This method reduces the size of the data being transferred compared to using a JSON string to represent an array.

Take a look at this sample code snippet:

function convertToBase64() {
  var file = document.querySelector('input[type=file]').files[0];
  var reader = new FileReader();
  reader.addEventListener("load", function () {
    document.getElementById("output").value = reader.result;
  }, false);
  
  if (file) {
    reader.readAsDataURL(file);
  }
}
<input type="file" onchange="convertToBase64()" />
<br/>
<textarea id="output"></textarea>

Answer №2

If you're looking to handle form data in an efficient way, consider using FormData.

Here's a simple JQuery example:

var formData = new FormData();
$(':input', this).each(function (){
    if(this.name){
        var value = this.value;
        if(this.type == 'file'){
            value = this.files[0]; // TODO: if "input file multiple" is needed, loop through each value
        }
        formData.append(this.name, value);
    }
});

$.ajax({
    url: 'http://example.com/xhr',
    type: "POST",
    data: formData,
    processData: false,
    contentType: false,
    error: function (request, textStatus, errorThrown){
        console.log(textStatus);
    },
    success: function (data, textStatus, request){
        console.log(data);
    }
});

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

Adjust the CSS for the "a" tag's "title" attribute

I am using jquery.fancybox to create an image modal on my website. I have noticed that I can add a description using the title attribute. However, when the description is too long, the text is displayed on a single line and some of it disappears. How can ...

Encountered an issue while trying to add images and text simultaneously in asp.net

I am trying to modify my code by adding an image along with the text. Here is the updated code: $(".ChatSend").click(function () { strChatText = $('.ChatText', $(this).parent()).val(); var recievertext= $('.ausern ...

Ensuring Consistent Data in Web Forms When Editing a User's "Points" Field

In the process of creating a booking system, I am faced with an issue regarding how points are allocated to users. An admin can assign points to a user through a form, which the user then uses when booking a slot. The problem arises when the admin opens th ...

Attempting to categorize JSON object elements into separate arrays dynamically depending on their values

Here's the JSON data I'm currently working with: ?$where=camis%20=%2230112340%22 I plan to dynamically generate queries using different datasets, so the information will vary. My main objective is to categorize elements within this array into ...

Understanding the impact of event loop blocking and the power of asynchronous programming in Node JS

I am new to Node.js programming and I really want to grasp the core concepts and best practices thoroughly. From what I understand, Node.js has non-blocking I/O which allows disk and other operations to run asynchronously while JavaScript runs in a single ...

When using jQuery's .text() method, it updates the "source" content without affecting the actual DOM

Here is a scenario I am working on with jQuery: When the user clicks on a div An ajax call is triggered to save data in the database After receiving the callback, an update message is displayed <--everything good until here Now, if the user clicks on ...

Retrieving deeply nested data without being restricted by the value of the database, MongoDB

Is there a way to retrieve the UUID from the "matches" field in MongoDB using pymongo, regardless of its value? Here is an example query: receiver = {'_id' : requests['id']} match = {'matches.id' : requests['match' ...

Trouble with getting started on the Google Sheets API (v4) tutorial

I'm currently working my way through a tutorial that can be found at the link below: https://developers.google.com/sheets/api/quickstart/nodejs# When I reach the step of running the quick start file (node quickstart.js), I encounter the following err ...

Converting Spring MVC Response to Snake Case Format

I am encountering a challenge and could use some assistance. Specifically, I have defined a POJO like so: private String uid; private String userName; private String firstName; private String lastName; The structure of my DAO appears to be: @Override pu ...

Enable the text to wrap around an interactive object that the user can freely manipulate

Looking for a solution where I can have a floating div that can be moved up and down using javascript while the text wraps around it seamlessly. Similar to how an object positioned in a word document behaves, I want the text to flow around the div both ab ...

The Vite manifest file could not be located in the designated path: C:xampphtdocslolaboutpublicuild/manifest.json

"Error: Vite manifest not found at: C:\xampp\htdocs\vrsweb\public\build/manifest.json" Please start the development server by running npm run dev in your terminal and refreshing the page." Whenever I attempt to acce ...

Can $refs cause issues with interpolation?

I'm currently learning Vue.js and the course instructor mentioned that modifying the DOM element using $refs should not affect interpolation. In fact, any changes made directly to the DOM will be overridden by interpolation if it exists. However, in m ...

What yields greater performance in MongoDB: employing multiple indexes or creating multiple collections?

Currently, I am developing an application that validates users through various 3rd party services such as Facebook and Google. Each user is assigned a unique internal id (uuid v4) which corresponds to their 3rd party ids. The mongoose schema for my user do ...

Steps to display a JSX component stored in a variable

Presently, I am implementing an if/else statement within my code to determine the content that will be displayed in the JSX element named 'signupMessage'. Subsequently, I render the contents of this 'signupMessage' element. render() { ...

How can I open a new window, redirect the current one, and bring focus to the new window using JavaScript?

Trying to troubleshoot a problem I'm having with the following setup: - Using SAP Portal, I am launching an HTML page containing this code. - The goal is for the HTML page to open a new window. - Once the new window opens, the original HTML page ...

Unable to access a nested JSON object that has a repeated name

I'm relatively new to working with JSON, so the issue I'm facing may be simple, but I haven't been able to find a similar problem on stackoverflow. Here's my question: My goal is to access a nested JSON object like: pizza.topping.ratin ...

Utilize tags as properties in Vue.js by selecting them

I am attempting to retrieve a value from a select tag and use it in an object property. Below is the HTML code: <div id="app"> <h3>{{title}}</h3> <div class="form"> <div class="form-group"> <div ...

Having trouble with Bootstrap 4 maintaining consistent width when affixing the sidebar

Hello there, I'm currently working with Bootstrap 4 and trying to implement affix on the sidebar. I have set up three columns for the sidebar and made them fixed under certain conditions. However, I am facing an issue where the width of the sidebar ch ...

Enhancing Chat: Updating Chat Messages in Real-Time with Ember.js and Firebase

I recently started working with ember.js and firebase. Right now, I have successfully implemented a feature to post messages and view them in a list format as shown below: //templates/show-messages.hbs {{page-title "ShowMessages"}} <div clas ...

Synchronize React Hooks OnchangeORSync React Hooks On

Currently, I am in the process of transitioning my app from using a class model to utilizing hooks. In my code, there is a dropdown list where the onChange method performs the following function: filter(event) { this.setState({ selectedFilter: ...