javascript - Angular 2 同步文件上传

标签 javascript angular typescript

我正在尝试将文件上传到 Web API,该 API 使用 Angular 2 应用程序将文件作为字节数组。

我无法将字节数组从 Angular 2 页面传递到 Web API。看起来 File Reader 读取方法是异步的。如何将其作为同步调用或等待文件内容加载后再执行下一行代码?

下面是我的代码

//attachment on browse - when the browse button is clicked
//It only assign the file to a local variable (attachment)
fileChange = (event) => {
    var files = event.target.files;
    if (files.length > 0) {
        this.attachment = files[0];
    }
}

//when the submit button is clicked
onSubmit = () => {


        //Read the content of the file and store it in local variable (fileData)
        let fr = new FileReader();
        let data = new Blob([this.attachment]);
        fr.readAsArrayBuffer(data);
        fr.onloadend  = () => {
            this.fileData = fr.result; //Note : This always "undefined"
        };


        //build the attachment object which will be sent to Web API
        let attachment: Attachment = {
            AttachmentId: '0',
            FileName: this.form.controls["attachmentName"].value,
            FileData: this.fileData
        }

        //build the purchase order object
        let order: UpdatePurchaseOrder = {
            SendEmail: true,
            PurchaseOrderNumber: this.form.controls["purchaseOrderNumber"].value,
            Attachment: attachment
        }

        //call the web api and pass the purchaseorder object
        this.updatePoService
            .updatePurchaseOrder(this.form.controls["purchaseOrderRequestId"].value, order)
            .subscribe(data => {
                if (data) {
                    this.saveSuccess = true;
                }
                else {
                    this.saveSuccess = false;
                }
            },
                error => this.errors = error,
                () => this.res = 'Completed'
            );
    }

任何提示都会有用。

问候, -艾伦-

最佳答案

您不能使此异步调用同步。但是你可以利用 observables 来等待文件被读取:

//when the submit button is clicked
onSubmit = () => {
    let file = Observable.create((observer) => {
        let fr = new FileReader();
        let data = new Blob([this.attachment]);
        fr.readAsArrayBuffer(data);
        fr.onloadend = () => {
            observer.next(fr.result);
            observer.complete()
        };
        fr.onerror = (err) => {
            observer.error(err)
        }
        fr.onabort = () => {
            observer.error("aborted")
        }
    });
    file.map((fileData) => {
            //build the attachment object which will be sent to Web API
            let attachment: Attachment = {
                AttachmentId: '0',
                FileName: this.form.controls["attachmentName"].value,
                FileData: fileData
            }
            //build the purchase order object
            let order: UpdatePurchaseOrder = {
                SendEmail: true,
                PurchaseOrderNumber: this.form.controls["purchaseOrderNumber"].value,
                Attachment: attachment
            }
            return order;
        })
        .switchMap(order => this.updatePoService.updatePurchaseOrder(this.form.controls["purchaseOrderRequestId"].value, order))
        .subscribe(data => {
                if (data) {
                    this.saveSuccess = true;
                } else {
                    this.saveSuccess = false;
                }
            },
            error => this.errors = error,
            () => this.res = 'Completed'
        );
}

关于javascript - Angular 2 同步文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42905394/

相关文章:

angular - 在 Ionic 中使用表单会引发错误 : NodeInjector: NOT_FOUND [ControlContainer]

javascript - 缩放图像时是否可以禁用滑动功能?

java - 如何将参数从 cordova HTTP 传递到 Spring Controller

javascript - TypeScript 构造函数语法

typescript - 检测到依赖循环.eslint with typeorm

reactjs - typescript 错误 : Type '{ onClick: () => void; }' is not assignable to type 'IntrinsicAttributes'

javascript - 带有 highcharts 的配对数据的分割条形图

javascript - 捕获VLC Webplugin的MediaPlayerPlaying事件

javascript - 使用 javascript 限制在特定 div 窗口上拖动 html 内的对象

javascript - 向 onKeyPress 函数添加参数