通过角度http请求发布文件

时间:2016-08-23 12:12:52

标签: javascript angularjs http

我正在使用angularjs,我正在尝试将图片与请求正文中的其他数据一起上传到django后端服务器。

我一直收到来自服务器的错误,告诉我我发送的图片不是文件。 (假设后端没有问题)

我尝试使用ng-file-upload(https://github.com/danialfarid/ng-file-upload)获取文件,然后通过angular本身发送。 (注意:我需要将其他数据与图片一起发送)所以我想将文件存储在变量中并将其传递到请求体中,如下所示:

$http({
          'method': "PUT",
          'url': "api/candidate-profiles/" + id,
          'data':data
})

由于文件存储在$ scope.file中,我尝试在http请求中使用它:

{"id": $scope.id,
"name": $scope.name,
"avatar":$scope.file}

数据是:

private Session createSmtpSession() 

我从后端收到验证错误,指出该头像不是文件。有什么帮助吗?

2 个答案:

答案 0 :(得分:0)

<强> HTML

CREATE FUNCTION convert_to_date (scolumn anyelement,rownumber numeric, format text) RETURNS timestamp AS $$
    BEGIN
        BEGIN
            RETURN cast(to_timestamp(scolumn, format) as timestamp  without time zone);
        exception when others then
INSERT INTO another_table(column_name, row_number, errval) VALUES (scolumn, rownumber, 'invalid-text-here')
            RETURN null;
        END;
    END;
$$ LANGUAGE plpgsql;

<强> jsfile

SELECT convert_to_date(some_column,row_number, 'DD/MM/YYYY') from some_table;

Code Download

demo click

答案 1 :(得分:0)

我认为您应该阅读文档,并查看一些示例,例如this

app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
    $scope.uploadPic = function(file) {
    file.upload = Upload.upload({
        url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
        data: {username: $scope.username, file: file},
    });

    file.upload.then(function (response) {
        $timeout(function () {
            file.result = response.data;
        });
    }, function (response) {
        if (response.status > 0)
          $scope.errorMsg = response.status + ': ' + response.data;
    }, function (evt) {
        // Math.min is to fix IE which reports 200% sometimes
        file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
    });
    }
}]);

http://jsfiddle.net/danialfarid/maqbzv15/1118/