Angular makes it easy to perform HTTP requests using the `http

Greetings! Here is the JSON data for "names" :

[
    {
        "file": "file1.zip",
        "date": "12-03-2016",
    },
    {
        "file": "file2.zip",
        "date": "24-06-2016",
    },
    {
        "file": "file3.zip",
        "date": "02-12-2016",
    }]

Here is my JavaScript file:

var app = angular.module('app', []);
    app.service('service', function($http, $q){
        var deferred = $q.defer();

        $http.get('newapi.json').then(function(data){
            deferred.resolve(data);
        });

        this.getNames = function(){
            return deferred.promise;
        }
    });
    app.controller('FirstCtrl', function($scope, service){
        var promise = service.getNames();
        promise.then(function(data){
            $scope.names = data.data;
            $scope.namesplit = $scope.names;
            $scope.namesplit.map(function(item) {
                item.time = new Date(item.date * 1000);
            });
            console.log($scope.namesplit);
        });
        });

And here is the corresponding HTML code:

<tr ng-repeat="name in names">
   <td>{{name.file}}</td>
   <td>{{name.date}}</td>
   <td><button>POST</button></td>
</tr>

My goal is to have a functionality where upon clicking the button, the "file" gets posted to the server using $http.post. I am looking for guidance on how to achieve this.

Answer №1

Extremely Easy HTML

<button ng-click="post()">Press Here</button>

Control Center

    $scope.post=function(){
$http.post(URL HERE, data-here, {    
 })
  .then(function onSuccess(response) {
    // Manage success
    var info = response.data;
    var statusCode = response.status;
    var statusMessage = response.statusText;
    var headersInfo = response.headers;
    var configSetting = response.config;
    ...
  }).
  catch(function onError(response) {
    // Manage issue
    var errorData = response.data;
    var errorCode = response.status;
    var errorMessage = response.statusText;
    var errorHeaders = response.headers;
    var errorConfig = response.config;
    ...
  });
  }

Answer №2

To successfully upload a file using the $http.post() function, you need to configure additional parameters such as headers and transformRequest.

Below is a straightforward example:

$scope.sendFileToServer = function(){
    var formData = new FormData();
    formData.append('file', file); 
    $http.post(uploadUrl, formData, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    })
    .success(function(){
    })
    .error(function(){
    });
}

Please note that in this demonstration, the 'file' variable represents the content of the file stored on the client's file system, while 'uploadUrl' refers to the URL of your service capable of handling the file upload request.

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

Error encountered: EPERM - Unable to perform operation on Windows system

Recently, I executed the following command: npm config set prefix /usr/local After executing this command, I encountered an issue when attempting to run any npm commands on Windows OS. The error message displayed was as follows: Error: EPERM: operation ...

Tips for creating a textarea element that resembles regular text format

I am working on creating an HTML list that allows users to edit items directly on the page and navigate through them using familiar keystrokes and features found in word processing applications. I envision something similar to the functionality of To achi ...

Activate ajax search in select2 by hand

I recently integrated the select2 plugin with jQuery into my website. For the most part, it functions perfectly. One particular feature I have is a search widget that utilizes select2 and remote data search. When I enter a search query using a keyboard ...

Issues arise in Angular 4 when the "Subscribe" function is repeatedly invoked within a for/switch loop

My array of strings always changes, for example: ["consumables", "spells", "spells", "consumables", "spells", "consumables", "spells", "characters", "characters", "consumables"] I iterate through this array and based on the index, I execute different .su ...

The RemoveEventListener function seems to be malfunctioning within Angular2 when implemented with TypeScript

I am currently incorporating three.js into Angular2. The code I am using is quite straightforward, as shown below. this.webGLRenderer.domElement.addEventListener('mousedown', ()=>this.onMouseDown(<MouseEvent>event), false); this.webGLR ...

The not:first-child selector targets all elements except for the first one in the sequence

This is a simple js gallery. I am using not:first-child to display only one photo when the page is loaded. However, it does not hide the other photos. You can view the gallery at this link: (please note that some photos are +18). My objective is to hide ...

Error: The function req.logIn is not valid

I'm currently in the process of creating a dashboard for my Discord bot, but I've encountered an error that reads as follows: TypeError: req.logIn is not a function at Strategy.strategy.success (C:\Users\joasb\Desktop\Bot& ...

Replacing URLs in Typescript using Ionic 3 and Angular

Currently facing some difficulties getting this simple task to work... Here is the URL format I am dealing with: https://website.com/image{width}x{height}.jpg My objective is to replace the {width} and {height} placeholders. I attempted using this func ...

When attempting to import a component from react-bootstrap, an error is thrown

Every time I try to use a component from 'react-bootstrap', I encounter a strange error. Here is a small example where I am importing the "HelpBlock" component. import PropTypes from 'prop-types'; import React from 'react'; i ...

The regular expression for email validation does not accurately verify the portion following the period

I'm currently working on validating email addresses in my HTML page using an Angular directive. From my perspective, a valid email address looks like this: [email protected] The regular expression I've been using allows for email addresse ...

Chrome App Experiencing Issues with DOM Loading

I am working on converting a simple HTML5 Snake game that utilizes canvas into a Chrome App. Below is the snippet of my original HTML file: <!DOCTYPE html> <html> <head> <title>Snake</title> <link rel=" ...

Guide to displaying a table enclosed in a div based on a selected value in a select dropdown?

I am attempting to retrieve the table options using the select question-picker: Here is what I have tried: $(document).ready(function() { var question_container = $('.question-picker option[value="1"]').parent(); console.log(question_cont ...

What could be causing the AntiForgeryToken validation to fail while implementing AngularJS in an ASP.NET MVC application?

I am encountering a problem with passing the correct AntiForgeryToken when using AngularJS $http service in an ASP.NET MVC application. Here are the solutions I have attempted: Setting HTTP Request headers with an httpInterceptor app.factory('ht ...

Is there a way to create a sequence where text fades in only after the previous text has completely faded out?

Currently, I am using JQuery to create a continuous slideshow of text values. However, after some time, multiple texts start to display simultaneously, indicating a timing issue. Even when hidden, the problem persists. My code includes 3 strings of text. ...

Creating a Border Length Animation Effect for Button Hover in Material-UI

I'm currently exploring Material-UI and trying to customize a component. My goal is to add a 'Border Length Animation' effect when hovering over the button. Unfortunately, I have yet to successfully implement this animation as intended. For ...

Accessing Rails controller information via a JavaScript AJAX request

In the process of developing a rails application, I have implemented code within the controller to interact with an API. Initially, I call the inventories endpoint, followed by separate calls to two other id endpoints (store_id and product_id) in order to ...

What is the best way to retrieve information from a JavaScript file?

Learning.vue <template> <div> <button @click="test()">test</button> </div> </template> <script> import records from './records.js' export default { data () { return { ...

Display refined outcomes on the search results page

In my app, the main feature is a search box on the homepage. Users can input their search queries and upon submission, they are redirected to a result page displaying the relevant results along with filtering options. The filtering functionality allows use ...

Getting a variable from outside of the observable in Angular - a step-by-step guide

I have an Observable containing an array that I need to extract so I can combine it with another array. this.builderService.getCommercialData() .subscribe( data=>{ this.commercialDetails = data; this.commercialDetailsArr ...

Generating a download link with an expiration feature in node.js or express for both frontend and backend operations

Hello everyone, I'm a beginner here and have recently started working with node.js and express.js. I am looking to implement a download link on my website that expires after a certain time, but I've been struggling with the code for about a week ...