简体   繁体   中英

Trying to submit file via form asynchronously using Angular $http

I am trying to submit a file asynchronously via Angular. This is the 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.

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. 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. Thanks.

should be in req.files and in order for that you'll need to use express.bodyParser(). If you use express of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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