【问题标题】:Get URL from a file upload post从文件上传帖子中获取 URL
【发布时间】:2018-03-18 13:59:39
【问题描述】:

我正在将一些元素上传到 S3。我在此链接中使用相同的示例:

JsFiddle

myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){

$scope.uploadFile = function(){
    var file = $scope.myFile;
    console.log('file is ' );
    console.dir(file);
    var uploadUrl = "/fileUpload";
    fileUpload.uploadFileToUrl(file, uploadUrl);
};

此时,它可以工作了,但是现在,我需要捕获上传文件的 url。我怎样才能做到这一点?我是新上传文件:/

myApp.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(){
        })
        .error(function(){
        });
    }
}]);

提前感谢。

【问题讨论】:

标签: javascript angularjs file-upload angularjs-http


【解决方案1】:

使用异步 API 创建服务时,返回 API 返回的承诺很重要:

myApp.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        ̶v̶a̶r̶ ̶f̶d̶ ̶=̶ ̶n̶e̶w̶ ̶F̶o̶r̶m̶D̶a̶t̶a̶(̶)̶;̶
        ̶f̶d̶.̶a̶p̶p̶e̶n̶d̶(̶'̶f̶i̶l̶e̶'̶,̶ ̶f̶i̶l̶e̶)̶;̶ 
        //RETURN the promise
        ͟r͟e͟t͟u͟r͟n͟  $http.post(uploadUrl, ̶f̶d̶,̶   ͟f͟i͟l͟e͟,͟  {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        }).then(function(response) {
            return response.data;
        }).catch(function(response) {
            console.log("ERROR: ", response.status;
            //IMPORTANT
            throw response;
        });
    }
}]);

另外如果服务器支持的话,直接上传文件效率更高。 formData API 使用内容类型 multipart/form-database64 编码,增加了 33% 的额外开销。

在控制器中,从返回的promise中提取数据:

$scope.uploadFile = function(){
    var file = $scope.myFile;
    console.log('file is ' );
    console.dir(file);
    var uploadUrl = "/fileUpload";
    var promise = fileUpload.uploadFileToUrl(file, uploadUrl);

    promise.then(function(data) {
        console.log(data);
    });

    return promise;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多