简体   繁体   English

尝试使用Angular $ http通过表单异步提交文件

[英]Trying to submit file via form asynchronously using Angular $http

I am trying to submit a file asynchronously via Angular. 我正在尝试通过Angular异步提交文件。 This is the HTML: 这是HTML:

<form ng-submit="videoSubmit()">
    <input id="upl-0"  type="file" name="upl" accept="video/ogg, video/mp4, video/webm">
    <input type="submit" value='Submit' />
</form>

My Angular code: 我的角度代码:

 $scope.videoSubmit = function() {

    var file = document.getElementById('upl-0').files[0];

    var formData = new FormData();
    console.log(file);
    formData.append("upl", file, file.name);
    console.log(formData);
    console.log(formData.getAll("upl"));

    $http({
            method: 'POST',
            url: "api/asset/upload-test",
            data: formData,
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
        .then(function(result) {
            console.log(result);
        });
 };

This definitely attaches the file to the formData object because it is displaying the right file data in the console. 这肯定会将文件附加到formData对象,因为它在控制台中显示了正确的文件数据。

Now I want to do something with this on the server, but in the meantime I just want to actually get this working, so this is all that's on the server: 现在,我想在服务器上对此进行操作,但是与此同时,我只想真正使它工作,所以这就是服务器上的全部内容:

 router.post('/api/asset/upload-test', function(req, res) {
    console.log(req.data);
    console.log(req.body);
 });

However somehow the server just doesn't receive the file, and displays undefined for req.data and {} for req.body. 但是,服务器不知何故不接收文件,对req.data显示undefined对req.body显示{} Why is this and how can I get this actually working in the same implementation, so without having to encode or decode the file in something like base64 or similar. 为什么这样做以及如何在同一实现中实际使用它,而不必使用诸如base64之类的东西对文件进行编码或解码。 Thanks. 谢谢。

should be in req.files and in order for that you'll need to use express.bodyParser(). 应该在req.files中,并且为此,您需要使用express.bodyParser()。 If you use express of course. 如果您当然使用快递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM