Using AngularJS to upload an image in Laravel without the need for a

Is there a way to upload an image using AngularJS without a form and then send it to Laravel? I'm struggling with the implementation, here is my current code:

<input type="file" name="file" accept="image/jpeg, image/png" id="file" ng-model="data.image">


$('input[type=file]').change(function () {
    $scope.img = this.files[0];
    var filePath = $("#file").val();
    var reader = new FileReader();
    reader.onload = function (e) {
        $('#image').attr('src',e.target.result);
        $scope.img["imgbase64"] = e.target.result;
    };
    reader.readAsDataURL(this.files[0]); 
});

I am making use of a service as shown below:

var imgSend = new FormData();
imgSend.append("file",$scope.img);
data["image"] = imgSend;
url = "maquinas";    
registroMaquinaServices.servicesRegistroMaquinaPost(url,data).then(function(promise){
    var requests = promise.data.response;
    console.log(requests);
})

The data is being sent to Laravel, you can check the screenshot https://i.sstatic.net/EghBR.png.

Thank you for any help or advice in advance!

Answer №1

If you're looking to simplify the process of handling image file uploads, consider using https://github.com/ghostbar/angular-file-model. This tool allows you to create a form object and easily send it to your Laravel server without encoding the image as base64. Below is an example of how you can achieve this:

$http({
    headers: {
        'Content-Type': undefined //intentionally set as undefined
    },
    method: method,
    url: url,
    data: $scope.data,
    transformRequest: function(data, headersGetter) {

        var formData = new FormData();

        angular.forEach(data, function(value, key) {
            formData.append(key, value);
        });

        return formData;
    }
})

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

Upon selecting a hyperlink, the function's value ought to be saved within a text box

Some programming languages I'm working with are PHP, Javascript, and HTML I've created a PHP function that is stored in page2.php: function pot() { does something; returns a value; } In another page (page1.php), there is a link and a textbox: ...

Enhance your THREE.js projects with dynamic textures using Promises

Can anyone offer guidance on how to utilize promises for loading textures in THREE.JS? I've looked into their functionality, but could really use a practical example. Specifically, I am attempting to load an image (img.png) onto a cube mesh. I prefer ...

Is there a way to install angular libraries manually and ensure all dependencies are included without relying on bower or npm?

Currently, I am facing an issue with importing data from an Excel spreadsheet into my Angular application. I came across a helpful guide to import them into UI-Grid using xlsx.js which seems like a good starting point for me. However, my challenge lies in ...

Tips for expanding the capabilities of Laravel's bcrypt function

I have created a custom PHP class that blends various hash algorithms, and I am interested in integrating it into Laravel's bcrypt() method. Currently, my approach involves accessing the AuthController and replacing bcrypt($data['password'] ...

strategies for sharing data in Angular 2

Seeking advice on data sharing within various components of an Angular 2 application. At the moment, my app structure is similar to that shown in this tutorial, where the AppComponent is bootstrapped by Angular and multiple components are routed from there ...

Consistently obtaining the same outcome in JavaScript, always

Is it possible to resolve this issue? I keep getting a result of less than 18 when trying numbers 1-100, even though the output should be for values under 18. In my HTML code, there is a <p> element with id="result", an input with id=&quo ...

Error message "The camera provided is invalid and not an instance of THREE.Camera" appears when attempting to render a cube using Three.js

I've been working on a small "engine" project using three.js to easily create and position objects. So far, I have set up the scene, renderer, and camera successfully. However, when attempting to render and attach a cube to my scene, I encounter an is ...

Issue with Chrome not triggering onMouseEnter event when an element blocking the cursor disappears in React

Important Note: This issue seems to be specific to Chrome Currently, React does not trigger the onMouseEnter event when a blocking element disappears. This behavior is different from standard JavaScript events and even delegated events. Below is a simpli ...

Saving multiple instances of an object using Mongoose

In my Mongoose model, I have a blog schema where each blog can have multiple comments attached to it. var mongoose = require('mongoose') , Schema = mongoose.Schema var blogScheam = Schema({ title: String, comments: ...

Developing maintenance logic in Angular to control subsequent API requests

In our Angular 9 application, we have various components, some of which have parent-child relationships while others are independent. We begin by making an initial API call that returns a true or false flag value. Depending on this value, we decide whether ...

How can I incorporate CSRF token into a POST request with AngularJS and Spring Security?

Within my AngularJS authService, I encounter an issue when sending a POST request with credentials and a username to a server endpoint on a different domain. Despite having a CORSFilter in place, I can only successfully POST data by disabling CSRF protecti ...

Effective method for JSON data parsing

Greetings everyone, I have a question regarding performance implications in JavaScript. I have a JSON query result as follows: [{'name': 'a'}, {'name': 'b'}] For another query, I need to manipulate it to the foll ...

The functionality of cancel and revert in jQuery Sortable is not behaving as anticipated

Issue (Link to problem demo on jsFiddle) I'm encountering difficulties with the revert setting when used alongside the cancel method in jQuery sortable. The cancel method, as outlined in the jQuery Sortable documentation, explains: Cancels a chang ...

Need assistance with organizing the table number?

I am looking for a way to format all table <td> elements with the class "contribution" using the method .toLocaleString(); or a similar technique that can add commas and currency formatting. The table will never exceed 200 rows, which may be relevant ...

Sequenced thunk execution during rendering

My application automatically retrieves user information upon rendering. When the app is first launched, it uses the getUserInformation() function to fetch this data. Users do not need to log in manually as the app operates within the company's interna ...

What is preventing the data property from updating in setInterval?

Looking for a way to increase the speed of the props while my marker is moving? Currently, the speed only updates when the pause button is clicked. How can I automatically update this.speed when clicking the speed button? I have defined the speed prop in ...

"I'm looking for a way to efficiently pass variables between routes in Express when working with

Having some trouble passing variables from Express to node.js. Specifically, I'm trying to retrieve the IP address in the .js file. Here's my code snippet: app.get('/', function(req, res) { app.set('ipAddr' , req.ip); res ...

Personalize the close button on the modal

Utilizing the angular strap modal in my controller looked like this: $scope.modal = $modal({ scope: $scope, title: 'My Title', content: text, html: true, contentTemplate: 'views/partials/myTemplate.html', show: ...

How come the Array object transforms into an empty state when an input file is passed as an array element in an ajax request without

When attempting to upload a file without assigning it to an array, the process works fine. However, when trying to assign the file object as an element of an array, $_FILES becomes empty. HTML <input type='file' name='image' class= ...

What is the best way to send an object array from an express function to be displayed on the frontend?

//search.js file import axios from "axios"; export function storeInput(input, callback) { //input = document.getElementById("a").value; let result = []; console.log(input); if (!callback) return; axios.post("ht ...