klo*_*one 4 typescript azure-blob-storage
Azure Blob 服务允许我们传递一个取消过滤器,该过滤器可用于取消上传(示例:如何取消使用 BlobService.createBlockBlobFromBrowserFile 开始的上传?)。它对于单个上传效果很好,但对于客户端尝试上传多个文件的情况则效果不佳。问题是取消过滤器是服务本身的属性,而不是单个上传,因此取消一个上传会取消所有上传。有没有什么方法(通过打字稿/JavaScript 客户端)可以取消一个上传,同时让其他人不受干扰?
该包azure-storage是遗留的。现在微软建议客户使用新的sdk V12 @azure/storage-blob。如果使用新的SDK,我们可以使用AbortController取消一项操作。欲了解更多详情,请参阅此处。
例如(我在角度应用程序中测试它)
npm install @azure/storage-blob @azure/abort-controller
Run Code Online (Sandbox Code Playgroud)
(window as any).global = window;
(window as any).process = require( 'process' );
(window as any).Buffer = require( 'buffer' ).Buffer;
Run Code Online (Sandbox Code Playgroud)
<label class="btn btn-default">
<input type="file"
id="file"
multiple
(change)="onFileChange($event)">
</label>
<div *ngFor="let item of fileInfos" class="mb-2">
<span>{{ item.file.name }}</span>
<div class="progress">
<div
class="progress-bar progress-bar-info progress-bar-striped"
role="progressbar"
attr.aria-valuenow=" {{ item.value }}"
aria-valuemin="0"
aria-valuemax="100"
[ngStyle]="{ width: item.value + '%' }"
>
{{ item.value }}%
</div>
</div>
<button class="btn btn-primary" (click)='item.upload()'>upload</button>
<button class="btn btn-primary" (click)='item.cancel()'>cancel</button>
</div>
Run Code Online (Sandbox Code Playgroud)
FileInfo类import {AbortController} from '@azure/abort-controller'
import {BlobServiceClient,AnonymousCredential} from '@azure/storage-blob'
export class FileInfo{
file : File
value=0
private controller = new AbortController()
constructor(message: File) {
this.file = message;
}
async upload(){
try {
const blobServiceClient= new BlobServiceClient('https://<accountNmae>.blob.core.windows.net/?<sas token>',
new AnonymousCredential)
const containerClient= blobServiceClient.getContainerClient('<>')
const blob= containerClient.getBlockBlobClient(this.file.name)
console.log(`start uploading file ${this.file.name}`)
const total =this.file.size
await blob.uploadData(this.file,{
abortSignal: this.controller.signal,
blobHTTPHeaders:{blobContentType: this.file.type},
blockSize: 4*1024*1024,
onProgress : (ev) =>{
console.log(`You have uploaded ${ev.loadedBytes} bytes`);
this.value=Math.round(100 * ev.loadedBytes/ total);
}
})
console.log(` upload file ${this.file.name} successfully`)
} catch (error) {
console.log(`cannot upload file ${this.file.name}, it return error ${error}`)
}
}
cancel(){
this.controller.abort()
console.log(`cancel uploading file ${this.file.name}`)
}
}
Run Code Online (Sandbox Code Playgroud)
...
fileInfos: Array<FileInfo> =[]
onFileChange(event:any) {
this.fileInfos=[]
for (var i = 0; i < event.target.files.length; i++) {
var file =event.target.files[i]
this.fileInfos.push( new FileInfo(file))
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1829 次 |
| 最近记录: |