-->

Upload a file from a local directory using Angular

2019-09-13 02:43发布

问题:

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 need to do is upload these images into an images folder in my project locally. I don't need to do anything fancy. Am I able to get away with only using HTML5 or do I have to use JavaScript or jQuery? If I do need js or jq, what would the code look like?

Here is my partial:

<div class="form-group">
       <label>Please Upload your Images</label>
       <input type="file" class="form-control-file" id="inputFile" multiple>
</div>

回答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.



回答2:

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

<input type=file my-files="files" /><br>

my-files Directive

app.directive("myFiles", function($parse) {
  return function linkFn (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:

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

The xd-href Directive:

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

The DEMO on PLNKR.



回答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. .