无法从客户端向nodejs服务器发送文件数据

时间:2015-01-07 07:27:38

标签: javascript angularjs node.js file-upload

我在Angular js(v1.3.4)中创建简单的文件上传模块。我正在使用Nodejs服务器端。 我正在使用https://github.com/danialfarid/angular-file-upload库。它看起来很直接,但我坚持基本步骤。

的index.html

<div ng-controller="FileUploadController">   
        <input type="file" ng-file-select="onFileSelect($files)" multiple>  
</div>

controller.js

  $scope.onFileSelect = function($files) {

                for (var i = 0; i < $files.length; i++) {
                    var file = $files[i];
                    $scope.upload = $upload.upload({
                        url: 'http://localhost:8080/file-transfer/123/upload', 

                       // headers: {'Content-Type': undefined},
                       //     withCredentials: true,
                       //     transformRequest: angular.identity,
                       file: file       
                    }).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);
                        });
                }

在服务器端,我使用multer进行多部分。 客户端正在向服务器发送请求但不发送文件数据。

app.all('/file-transfer/:id/upload', function (req, res) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
    console.log(req.body);     // prints - {}
    console.log(req.files);   // prints -  {}
});

请求标题 -

Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Access-Control-Request-Me...    POST
Cache-Control   no-cache
Connection  keep-alive
Host    localhost:8080
Origin  http://localhost
Pragma  no-cache
User-Agent  Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0

我使用了与存储库示例相同的代码。也许我错过了一些东西。

注意 - 当我使用没有角度的简单html 5表单或使用$ http.post时服务器代码正常工作。

编辑:这是CORS问题,请阅读答案评论。

1 个答案:

答案 0 :(得分:0)

我正在使用相同的库,我的客户端代码中唯一不同的是我发送了method: 'POST'标头:

            $scope.upload = $upload.upload({
                url: '/api/uploads', //upload.php script, node.js route, or servlet url
                // method: 'POST' or 'PUT',
                method: 'POST',
                // headers: {'header-key': 'header-value'},
                // withCredentials: true,
                data: { type: 'profileImage' },
                file: file//, // or list of files: $files for html5 only
                // fileName: 'doc.jpg' or ['1.jpg', '2.jpg', ...] // to modify the name of the file
                /* customize file formData name ('Content-Desposition'), server side file variable name.
                 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 (e) {
                console.log('percent: ' + parseInt(100.0 * e.loaded / e.total));
            }).success(function (data, status, headers, config) {
                // file is uploaded successfully
                console.log(data);
                $scope.user.profileImages = data;
                $rootScope.$emit('message', { text: "Your profile image has been updated." });
            }).error(function(data){
                if ( data.error === 'UnsupportedFiletype' ) {
                    $rootScope.$emit('message', { type: 'error', text: "Woops, we don't support that filetype." });
                }
            });

编辑:解决方案是恰当地提供cors标题:

npm install corsapp.use(cors())