Is there a way to upload files in AngularJS without using AJAX or jQuery?

Currently, I am looking to create a gallery that allows for the uploading of multiple images. While I have come across some options that utilize ajax to immediately send the files, I prefer a solution that involves form submission.

In addition, I would like the ability to display thumbnails of the files before they are uploaded.

Is this feasible?

Answer №1

To accomplish this task, follow these steps:

<form ng-submit="uploadFile()" class="form-horizontal" enctype="multipart/form-data">
                <input type="text" name="username" ng-model="userName"/>
               <input type="file" name="image" ng-model="document.fileInput" id="file"  />
               <input type="file" name="docu" ng-model="document.fileInputTwo" id="fileTwo"  />
               <input type="text" class="col-sm-4" ng-model="document.title" id="title" />
               <button class="btn btn-primary" type="submit">
                     Submit
                </button>
            </form>

Additionally, include the following JavaScript code snippet for handling file uploads.

$scope.uploadFile = function() {

                    var formData=new FormData();
                    console.log(file);               
                    formData.append("file",file.files[0]);
                    formData.append("docu", fileTwo.files[0]);                  
                    formData.append("name", $scope.userName);

                    $http({
                          method: 'POST',
                          url: 'rest/newDocument',
                          headers: { 'Content-Type': undefined},
                          data:  formData,
                          transformRequest: function(data, headersGetterFunction) {
                            return data; // do nothing! FormData is very good!
                        }
                    })
                    .success(function(data, status) {                       
                            alert("Success ... " + status);
                    })
                    .error(function(data, status) {
                            alert("Error ... " + status);
                    });
              };

Remember to trigger the uploadFile() method upon button click within the form-submission process. To display a preview of the uploaded file, utilize the FileReader HTML5 API.

Answer №2

Illustration inspired by https://github.com/danialfarid/angular-file-upload

const MyController = [ '$scope', '$upload', function($scope, $upload) {
  $scope.onFileSelect = function($files) {
    //$files: an array of selected files, each with name, size, and type.
    $scope.files = $files;
  }
  $scope.callMeLater = function(){
    const $files = $scope.files;
    for (let i = 0; i < $files.length; i++) {
      const file = $files[i];
      $scope.upload = $upload.upload({
        url: 'server/upload/url', //upload.php script, node.js route, or servlet url
        // method: 'POST' or 'PUT',
        // headers: {'header-key': 'header-value'},
        // withCredentials: true,
        data: {myObj: $scope.myModelObj},
        file: file, // or list of files: $files for html5 only
        /* set the file formData name ('Content-Desposition'). Default is 'file' */
        //fileFormDataName: myFile, //or a list of names for multiple files (html5).
        /* customize how data is added to formData. See #40#issuecomment-28612000 for sample code */
        //formDataAppender: function(formData, key, val){}
      }).progress(function(evt) {
        console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
      }).success(function(data, status, headers, config) {
        // file uploaded successfully
        console.log(data);
      });
      //.error(...)
      //.then(success, error, progress); 
      //.xhr(function(xhr){xhr.upload.addEventListener(...)})// access and attach any event listener to XMLHttpRequest.
    }
    /* alternative way of uploading, send the file binary with the file's content-type.
       Could be used to upload files to CouchDB, imgur, etc... html5 FileReader is needed. 
       It could also be used to monitor the progress of a normal http post/put request with large data*/
    // $scope.upload = $upload.http({...})  see 88#issuecomment-31366487 for sample code.
  };
}];

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

"Troubleshooting issues with retrieving data from database using Ajax and

Help needed! I'm facing issues with a select code while using ajax. The codes seem to be incorrect and not working as intended. Here is the snippet of the problematic code: <?php require_once 'config/dbconfig.php'; if (isset($_REQUE ...

What is causing columns.render not to trigger when DataTable().draw() is invoked?

I'm wondering why the columns.render method is not part of the execution flow when using DataTable().draw(). For instance: HTML <table id="data"> <thead> <tr> <th>TimeColumn</th> < ...

Regain access to your account by resetting your password through the use of text messaging with Ionic

My current project involves working on the front end of a mobile app using Ionic and Angular, while utilizing an existing API and backend system. One of the key features I need to implement is the ability for customers to reset their password by receiving ...

Issue with Jquery .html() not adding content

Utilizing Jquery to dynamically update a list based on dropdown selections. After successfully fetching data and constructing the correct HTML content within the "item" variable, applying .html(item) does not result in the expected HTML updates. <div c ...

Adjust the divs right element by adding or removing 1 pixel for every size change in the browser

I have been exploring different approaches to achieve this task and it seems like using javascript might be the most effective way. I am currently dealing with a stubborn social icon container placement issue. More details on my previous question can be fo ...

jQuery causing trouble with AJAX in Rails

Currently, I am fetching a list of users from the controller side and generating the HTML code to append it. This is how I wrote the code: $.ajax({ type : "get", contentType : "application/json; charset=utf-8", url : "/users/sear ...

Encountering a Bad Request Response When Trying to Access WCF Service via Jquery Ajax

Encountered an issue when trying to call a WCF web service using jQuery Ajax, resulting in a bad request error without clear insight into the root cause. The service is not triggering any methods - neither success nor failure. Both the web service and the ...

The request to access the files at http://localhost:57722/api/Archivos returned a 404 error, indicating

When attempting to upload files from an API using AngularJS, I have encountered an issue. Files that are 20 MB or less upload successfully, but when trying to upload a file that weighs more, the console displays the message: "POST http://localhost:57722/ap ...

How can I transmit data to a jQuery web-service request?

I have been following various online tutorials but haven't had any luck so far. My goal is to create a basic example that successfully passes a value to a web service call. What am I missing here? I can achieve this easily with HttpHandlers...why is ...

Create your own AngularJS directive for displaying or hiding elements using ng-show/ng

Caution: Angular rookie in action. I'm attempting to craft a personalized widget that initially displays a "Reply" link, and upon clicking it, should hide the link and reveal a textarea. Here's my current progress, but unfortunately, it's n ...

What is the best way to use jQuery to display the character represented by an ASCII code &###?

Struggling with printing text? I am trying to append some content to an array, but it's showing special characters like &aacute; instead of the actual accented letters. Any suggestions on how to fix this issue? This is for a select tag, so I&apos ...

Convert TypeScript model to JSON while excluding properties with null values

When working with an Angular 4 App and a typescript model, I have defined a Person class as follows: export class Person{ fname:string, lname?:string } The 'lname' property in the model is optional. To populate the model in a component, I u ...

Superior method to ensure the child element's border overlaps with that of the parent

I am currently working on a project that requires a unique CSS effect: Let me explain exactly what I am trying to achieve: The main element (referred to as the title) has padding and a 2px bottom border. Inside this, there is a child element (known as ti ...

Trouble with updating the view when an array is modified in ng-repeat? It seems like using $scope.$apply() may not

When updating the array inside a function, the view does not automatically update. However, if you use console.log to check the array after pushing values, it shows the updated array. Even trying $scope.apply() inside $timeout did not solve this issue. Ja ...

What steps should I take to repair my jQuery button slider?

I am facing a challenge with creating a carousel of three images in HTML using jQuery. When the user clicks on the "Next" or "Previous" buttons, I want to scroll through the images one by one. However, I am struggling to hide the other images when one is d ...

As you scroll, the opacity gradually increases, creating a dynamic visual

Struggling to replicate a feature on a website where images gain opacity as you scroll down? Check out this site for reference: . While my current code somewhat achieves this effect, I'm having trouble figuring out how to apply a darker opacity gradua ...

Tips on sending error messages to an MVC view during an Ajax call

When using ajax to call a controller action method on an MVC button click event, there may be validation logic in the controller that needs to notify the user of any errors. Is there a way to send an error message to the ajax success event from the control ...

Issue with People Picker directive causing AngularJS validation to fail

I have implemented a SharePoint client-side people picker in my form using the directive from this GitHub repository. However, I am facing an issue where the validation of my form fails and the button remains disabled. When I remove the field, the validati ...

Preserving the table page number in Angular.js when updating a record in the application

I'm facing an issue with the datatable in my code on a transaction view page. Every time I update a child entry from the datatable and route to the child page, the selected page number is reset to one when I return to the view page. Can someone advise ...

What steps do I need to take to get this function up and running?

I am in the process of consolidating the functionality of two buttons that display different forms when clicked into a single function. Currently, when one button is toggled, the other form will hide. Below is the current implementation: $("#newaccount_fo ...