【问题标题】:Upload a file from a local directory using Angular 1.6.2使用 Angular 1.6.2 从本地目录上传文件
【发布时间】:2017-03-21 08:36:10
【问题描述】:

我正在使用 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>

【问题讨论】:

  • 您需要在服务器端获取文件并将其保存到磁盘

标签: javascript angularjs html angular-http


【解决方案1】:

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

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

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

【讨论】:

  • 非常感谢您对 cnorthfield 的快速响应!
【解决方案2】:

我使用一个指令来设置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


本地下载

使用带有download 属性的&lt;a&gt; 标记:

<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

【讨论】:

  • 非常感谢您的快速回复!如果本地文件夹是 /project/img,我将如何告诉我的代码将图像直接保存到本地文件夹中?
  • 下载时,浏览器会提示用户一个可以接受或取消的对话框。直接下载存在安全问题。用户不希望恶意网站在他们不知情的情况下下载文件。有关详细信息,请参阅MDN HTML Reference - &lt;a&gt; Tag
  • 没错,但从技术上讲,我是通过网站上传图像并将图像保存到我的本地 /project/img/ 目录中。我的笔记本电脑的行为就像服务器一样。
【解决方案3】:

感谢您的意见!该项目用于学校作业。尽管我可能没有使用其他语言的权限,但我最终可能会用 Python 编写此代码:Creation of a simple HTML file upload page using Python.

【讨论】:

    猜你喜欢
    • 2012-12-10
    • 2017-06-24
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    相关资源
    最近更新 更多