Skip to content Skip to sidebar Skip to footer

Upload A File From A Local Directory Using Angular 1.6.2

I am building an application using angular 1.6.2. I have an image upload button in one of my partials. I'm developing the site and running the server on my local laptop. All I n

Solution 1:

You need to send the data to the server to save it.

You can use the $http service to make a POST request to an endpoint provided by your backend service.

You cannot save the file on your server without a backend service to handle the request from the front end.

Solution 2:

I use a directive that sets the scope variable on the change event.

<inputtype=filemy-files="files" /><br>

my-files Directive

app.directive("myFiles", function($parse) {
  returnfunctionlinkFn (scope, elem, attrs) {
    elem.on("change", function (e) {
      scope.$eval(attrs.myFiles + "=$files", {$files: e.target.files});
      scope.$apply();
    });
  };
});

The DEMO on PLNKR.


How to POST a File Using the $http Service

When doing a POST of a file, it is important to set the Content-Type header to undefined.

var config = { headers: {
               "Content-Type": undefined,
              }
           };

$http.post(url, vm.files[0], config)
  .then(function(response) {
    vm.result = "SUCCESS";
}).catch(function(response) {
    vm.result = "ERROR "+response.status;
});

By default the AngularJS framework uses content type application/json. By setting Content-Type: undefined, the AngularJS framework omits the content type header allowing the XHR API to set the content type.

For more information, see MDN Web API Reference - XHR Send method


To Download Locally

Use an <a> tag with a download attribute:

<adownload="{{files[0].name}}"xd-href="data"><button>Download data</button></a>

The xd-href Directive:

app.directive("xdHref", function() {
  returnfunctionlinkFn (scope, elem, attrs) {
     scope.$watch(attrs.xdHref, function(newVal) {
       newVal && elem.attr("href", newVal);
     });
  };
});

The DEMO on PLNKR.

Solution 3:

Thanks for your input guys! This project is for a school assignment. Even though I may not have permission to use another language, I may wind up writing this in Python: Creation of a simple HTML file upload page using Python. .

Post a Comment for "Upload A File From A Local Directory Using Angular 1.6.2"