html5 - nodejs在后台如何处理angular $http.post()传过来的文件流?
ringa_lee
ringa_lee 2017-04-17 16:15:33
0
1
491

这两天在捣腾node文件上传的时候,前端使用了angular的$http.post()方法,将图片和文字存在FormData里面上传,但是后台能接收但是不能通过multiparty中间件解析。附上代码,求大神指教。

html

<form class="am-form" ng-controller = "formCtrl" enctype="multipart/form-data">
    <input type="text" class="am-form-field" ng-model = "formData.words" placeholder="说点什么吧..." required/>
    <p class="am-form-group am-form-file">
        <button type="button" class="am-btn am-btn-danger am-btn-sm am-btn-block">
            <i class="am-icon-cloud-upload"></i> 选择要上传的图片
        </button>
        <input id="doc-form-file" type="file" multiple = "multiple" required><!--$scope.formData = {};-->
    </p>
    <p id="file-list"></p>
    <button type="submit" ng-click = "smt()" class="am-btn am-btn-primary am-btn-block">提交</button>
</form>

js

var app = angular.module("trends", []);
    app.controller("formCtrl", function ($scope, $http) {
        $scope.formData = {};
        $scope.smt = function(){
            var fd = new FormData(); //初始化一个FormData实例
            var file = document.getElementById("doc-form-file").files[0];
            fd.append("words",$scope.formData.words);
            fd.append('file', file); //file就是图片或者其他你要上传的formdata,可以通过$("input")[0].files[0]来获取
            console.log(file)
            $http.post("/index", fd, {
                headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}
                    })
                    .success(function (data) {
                        console.log(data)
                    })
                    .error(function () {
                    });
        }


    })

node

router.post('/index', function (req, res) {
    console.log(req.body);
    var form = new multiparty.Form({
        encoding:"utf-8",
        keepExtensions:true  //保留后缀
    });//实例一个multiparty
    var uploadPath = path_up.join(path_up.resolve(__dirname,'../..'),"webapp/public/upload");
    form.uploadDir = uploadPath;
    form.parse(req, function(err, fields, files) {//开始解析前台传过来的文件
        console.log(err);
    })
    
});

我的效果:

Error: unsupported content-type

ringa_lee
ringa_lee

ringa_lee

Antworte allen(1)
迷茫

这个还是看下multiparty中的源代码吧,根据错误提示的行数及文件,你的post请求头header中的content-type不能匹配上一个正则

Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage