使用Angular 1.6.2从本地目录上载文件

时间:2017-03-18 21:55:13

标签: javascript angularjs html5 angular-http

我正在使用angular 1.6.2构建应用程序。我的一个部分中有一个图像上传按钮。我正在开发网站并在我的本地笔记本电脑上运行服务器。我需要做的就是将这些图像上传到我项目中的图像文件夹中。我不需要做任何花哨的事情。我只能使用HTML5,还是必须使用JavaScript或jQuery?如果我确实需要js或jq,代码会是什么样的?

这是我的部分内容:

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

3 个答案:

答案 0 :(得分:0)

您需要将数据发送到服务器以进行保存。

您可以使用$http服务向后端服务提供的端点发出POST请求。

如果没有后端服务来处理来自前端的请求,则无法在服务器上保存文件。

答案 1 :(得分:0)

我使用一个指令来设置change事件的范围变量。

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

my-files指令

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();
    });
  };
});

DEMO on PLNKR

如何使用$ http服务

发布文件

在对文件执行POST操作时,务必将Content-Type header设置为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;
});

默认情况下,AngularJS框架使用内容类型application/json。通过设置Content-Type: undefined,AngularJS框架省略了允许XHR API设置内容类型的内容类型标头。

有关详细信息,请参阅MDN Web API Reference - XHR Send method

本地下载

使用带有<a>属性的download代码:

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

xd-href指令:

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

DEMO on PLNKR

答案 2 :(得分:0)

感谢您的投入!这个项目是为了学校作业。即使我可能没有使用其他语言的权限,我也可以用Python编写这个:Creation of a simple HTML file upload page using Python.