Transmitting data via AJAX to a sails endpoint

Currently, I am facing an issue with a client-side component that generates a DataURL when a user uploads or takes a picture and then crops it. My goal is to send this DataURL via an AJAX call to a sails endpoint. As per the documentation provided by Sails, the endpoint will read the files using the following code:

req.file('file_name');

I am unsure about how to convert the DataURI into a format suitable for an AJAX call so that the endpoint can properly read the file from req.file. It would be helpful to see an example of setting up the call in any JavaScript or framework library to guide me through the implementation process.

Your assistance on this matter would be greatly appreciated.

Answer №1

When working on the client-side, you will need to convert the DataURL into form data before sending it to the route in your controller. There are helpful examples available here and here.

The endpoint for this process should look something like the following:


var uploadHandler = function(req, res) {
    req.file('avatar').upload({
        maxBytes: 4000000, // limit upload size to ~4MB
        dirname: '/tmp' // temporary directory
    }, function whenDone(error, uploadedFiles) {
        if (error) {
            if (error.code === 'E_EXCEEDS_UPLOAD_LIMIT') {
                return res.badRequest({ msg: error.message });
            }
            return res.serverError(error);
        }

        if (_.isEmpty(uploadedFiles)) {
            res.badRequest({ msg: "No file was uploaded." });
            return;
        }

        var filePath = uploadedFiles[0].fd;
        var fileType = uploadedFiles[0].type;

        if (!_.includes(['image/jpeg', 'image/png', 'image/gif'], fileType)) {
            res.badRequest({ msg: "Invalid file type." });
            return;
        }

        // Proceed with necessary actions...

    });
};

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

Setting a background image in vanilla-extract/css is a straightforward process that can instantly enhance

I am brand new to using vanilla-extract/CSS and I have a rather straightforward question. I am attempting to apply a background image to the body of my HTML using vanilla-extract, but I am encountering issues as I keep getting a "failed to compile" error. ...

Change the color of the Material UI InputLabel

Seeking assistance with my input label: <InputLabel>NAME</InputLabel> The text is currently displaying in white, which makes it difficult to read against the white background. Can someone provide guidance on how I can change the color to blac ...

Exploring the Mechanism Behind the Successful String Interpolation of a Variable Imported in my Angular 2 Application

After making some modifications to my Angular 2 application, I encountered a situation where something started functioning properly sooner than I expected. This has left me puzzled about why it's working in its current state. Specifically, I have an a ...

Error in calculation of $.post function in JQuery

I am facing an issue with my file delete.php, which contains the following code: <?php $folder = "./fak/"; $filename = $_POST['name']; unlink($folder.$filename); ?> Additionally, I have an index.html file with the below code: <html ...

Is there a way to determine the origin of a request using PHP?

I am looking for a way to retrieve the origin (domain name, not client IP) of an XHR request sent from some-client.com to some-rest.com using PHP. There are several possible solutions: One option is to use $_SERVER['HTTP_ORIGIN'], although I a ...

How far is the Google Maps Marker Distance?

I am interested in knowing how I can calculate the distance between my current location and a marker on the map, taking into account the curvature of the earth. Below is my JavaScript code: var map; function initMap(){ //constructor creates a new map - on ...

Contrasting onevent with addEventListener

After studying various DOM events, I attempted to implement the 'blur' event on the HTML body. My first attempt was with onblur document.body.onblur = () => { dosomething(); } and I also tried using AddEventListener document.body.addEven ...

What is preventing me from displaying the results on the webpage?

Currently, I am utilizing Express alongside SQLite and SQLite3 modules. However, upon running the server, the data fails to display on the initial request. It is only after a page refresh that the data finally appears. I attempted a potential solution by ...

How can you make the coordinates of the cursor track the cursor when it hovers over a rectangle?

The code provided below will constantly display the cursor's coordinates right below the cursor: function displayCursorCoordinates(e) { var x = event.clientX; var y = event.clientY; var coordinates = "(" + x + ", " + y + ")"; document.getEl ...

Steps to create a dynamic <div> that is only visible within a parent <div>

First of all, I want to express my gratitude for welcoming me into the group. I am seeking assistance with an inquiry regarding jQuery animation. The specific animation in question can be seen on the navigation menu items of this template from Template Mon ...

Utilizing JavaScript libraries in a TypeScript project: A step-by-step guide

Currently, I am working on an existing TypeScript AngularJS project and looking to incorporate d3js. However, due to restrictions with the corporate proxy, I am unable to use tools for downloading or managing dependencies. As a result, I have opted for man ...

Sorting through JSON information using JQUERY

Struggling with filtering data using jQuery and JSON. I need to exclude objects with the ID "234" or the sender named "Alan Ford" in order to create separate messaging systems for Inbox and Outbox. Directly manipulating the JSON is not an option. Here&apo ...

Utilizing CodeIgniter Controller for Handling JSON Requests via AJAX

My challenge lies in sending a form using CodeIgniter via AJAX and attempting to receive the response in JSON format. However, I encounter an issue where I can only view the response when I open my developer tab (although unsure if that's the actual r ...

What is the best method for transferring data from the first table to the second table in Angular?

I am looking to transfer data (Item and Price) from the first table to the second table and increase the Quantity field in the Second table upon clicking on an Item in the First Table. I am currently developing in Angular 9. First Table: Code | Item | Pr ...

Modify the name format using an AngularJS directive

I've been struggling to understand how to effectively write AngularJS directives, even after reading various blogs. The issue I am facing is with an array of names in the format "lastname, firstname". My goal is to create a directive that will display ...

Why won't my Chrome content script load even though I have the correct syntax and have tried troubleshooting?

I'm facing an issue with my extension where the file content.js is not being loaded on any webpage despite trying multiple troubleshooting steps. I've tried different permissions, changing site patterns, reinstalling, restarting Chrome, adjusting ...

Can you combine multiple items in PaperJS to move them collectively?

I'm working on a PaperJS project that involves numerous circles that can move independently. In addition to this, I would like each circle to have PointText at its center acting as a label. However, instead of having to manually animate each label ev ...

What is the best way to pass the value of a selected option to an express server

<label for="exampleFormControlSelect1"> <strong>Please Select the Number of PDFs to Merge:</strong> </label> <select class="form-control" id="exampleFormControlSelect1"> <option name=" ...

In order for the AngularJS SPA to detect the JWT token stored in local storage, it must be re

How are you doing? Today, I am seeking assistance with resolving a token authentication issue (jwt) in my SPA AngularJS application. I am using NodeJS in the backend. Upon logging in, the credentials are validated in the backend. Upon successful validati ...

The title of the homepage is showing up behind the AppBar. Any suggestions on how to correct this?

I encountered an issue with my appBar where the homepage was appearing behind it instead of below it. Here is a snapshot of the problem: https://i.stack.imgur.com/27LjB.png Below are the codes for the AppBar: const Header = () => { const [value, setV ...