gpt4 book ai didi

javascript - Angular 工厂 : update scope with progress during upload

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:02:47 24 4
gpt4 key购买 nike

我写了一个处理上传到 S3 的 Angular 工厂:

'use strict';

angular.module('myApp.s3', [])
.factory('S3', function ($q) {
var aws = { ... }

var progress = 0;

function getFileName(fileURI) {
return fileURI.split('/').pop();
}

return {
progress: progress,
upload: function (fileKey, fileURI, mimeType) {
var fileName = getFileName(fileURI);
if (fileName === '') {
console.log('File name can\'t be empty');
return;
}

var defer = $q.defer();
defer.promise.then(function (event) {
alert(JSON.stringify(event));
console.log(event);
}, function (error) {
alert(JSON.stringify(error));
console.log(error);
});

var fileTransfer = new FileTransfer();
var fileUploadOptions = new FileUploadOptions();
fileUploadOptions.fileKey = 'file';
fileUploadOptions.fileName = fileName;
fileUploadOptions.chunkedMode = false;
fileUploadOptions.params = {
'key': fileKey,
'AWSAccessKeyId': aws.access_key_id,
'acl': aws.acl,
'policy': aws.policy,
'signature': aws.signature
};

fileTransfer.upload(fileURI, encodeURI('https://' + aws.bucket + '.s3.amazonaws.com/'),
defer.resolve, defer.reject, fileUploadOptions);
fileTransfer.onprogress = function (progressEvent) {
if (progressEvent.lengthComputable) {
progress = (progressEvent.loaded / progressEvent.total) * 100;
console.log(progress);
} else {
//loadingStatus.increment();
}
};

return defer.promise();
}
};
});

这段代码工作正常,文件被上传到 S3。进度日志也在工作。当我在 Controller 中使用这个工厂并将进度绑定(bind)到范围时,我在我的范围内看不到进度更新。我猜这是因为作用域没有获得更新事件。

我见过一种变通方法,其中工厂使用范围进行初始化,并在工厂内调用 scope.apply()。我不认为这是在 Angular 中执行此操作的正确方法,但我也不知道正确的方法。有什么建议吗?

最佳答案

@Dmitry Tolmachov 的回答肯定有效,但我会使用 defer.notify,因为您已经在使用 promise ,并且因为使用通知,您不需要手动调用摘要周期:

fileTransfer.onprogress = function (progressEvent) {
if (progressEvent.lengthComputable) {
progress = (progressEvent.loaded / progressEvent.total) * 100;
console.log(progress);
defer.notify(progress);
} else {
//loadingStatus.increment();
}
};

然后在你的 Controller 中使用它 were .then(sucess,error,notify)

对比:Angularjs HTTP service POST progress event

关于javascript - Angular 工厂 : update scope with progress during upload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32393548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com