【问题标题】:File upload in ExpressJS and AngularJS using the REST API使用 REST API 在 ExpressJS 和 AngularJS 中上传文件
【发布时间】:2014-07-02 08:44:44
【问题描述】:

我是 AngularJS 和 Node.js 的新手。

我想使用 REST API、AngularJS 和 Express.js 实现文件(.pdf、.jpg、.doc)上传功能。

我试图从Use NodeJS to upload file in an API call 获得一个想法,但我仍然不清楚如何在 REST API 中使用 AngularJS 和 Express.js 上传文件。

谁能通过基本示例向我解释如何使用 REST API 在 AngularJS 和 Express.js 中上传文件?

【问题讨论】:

标签: javascript node.js angularjs rest express


【解决方案1】:

我最近一直在处理类似的问题。问题是,角度对输入类型“文件”没有最好的支持,因为你不能以两种方式绑定它。这就是人们为此制定自定义指令的原因。我使用的那个有一些很好的例子。

它叫angular-file-upload

【讨论】:

  • 现在我可以将文件发送到我的 nodejs 服务器,但是如何获取该文件并将其保存在某个目录中?
【解决方案2】:

参考: https://github.com/danialfarid/angular-file-upload
我已经使用以下代码解决了这个问题:

Angularjs

HTML
<input type="file" ng-file-select="onFileSelect($files)" multiple>
JS
  $scope.onFileSelect = function($files) {
    //$files: an array of files selected, each file has name, size, and type.
    for (var i = 0; i < $files.length; i++) {
      var 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 is 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.
  };

Nodejs 使用 expressJS

var path = require('path'),
    fs = require('fs');
var tempPath = req.files.file.path,
    targetPath = path.resolve('./uploadFiles/' + req.files.file.name);
fs.rename(tempPath, targetPath, function(err) {
if (err) throw err;
console.log("Upload completed!");

【讨论】:

    猜你喜欢
    • 2015-04-10
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多