Angular post json with file object

2019-08-31 17:02发布

I'm trying to make a post call with a simple object that has this structure:

{"name": "file.txt", "file": file}

file is an object I get from an input file.

I have tried to make this call but i can't submit my object:

var elements = $element[0];
var file = elements.getElementsByTagName('input')[0].files[0];
this.fileName = file.name;

var formData = new FormData();
formData.append('file', file);

var url = 'http://localhost:8080/upload';
var config = {
    transformRequest: angular.identity,
    headers: {'Content-Type': undefined}
};
$http.post(url, formData, config)
.success(function(data){
    $log.info(data);
})
.error(function(err){
    $log.error(err);
});

Any ideas on why this isn't working?

1条回答
再贱就再见
2楼-- · 2019-08-31 17:14

I recently had to do something smilar, it took a lot of fenagling to get the request to go through, but this configuration finally worked for us.

    sendObj.append("file", fileObj.file, fileObj.file.name);
    $http({
            headers: {'Content-Type': undefined},
            processData:false,
            method: 'POST',
            cache: false,

            url: sendUrl,
            data: sendObj,
            transformRequest: function(data, headersGetterFunction) {
                return data; // do nothing! FormData is very good!
            }
        })

On a side note, it also took a lot of messing about on the server side so depending on what you have, you may need to do something else. This was for our Spring server.

查看更多
登录 后发表回答