gpt4 book ai didi

file-upload - Angular2上传文件的方法

转载 作者:太空狗 更新时间:2023-10-29 16:48:09 25 4
gpt4 key购买 nike

我必须连同图片一起提交表格。我已经尝试过此代码(通过多种方式)但对我不起作用。有没有人有使用 angular2 上传文件的工作演示,请帮助我。

组件.html

    <form class="form-horizontal" role="form" >

<div class="form-group">
<label class="control-label col-sm-4" for="myname" style="">Name<span class="asterisk">*</span></label>
<div class="col-sm-7">
<div>
<input type="text" class="form-control" id="myname"
[(ngModel)]="myfile.name">
</div>
</div>
</div>


<div class="form-group">
<label class="control-label col-sm-4" for="myimage">Image</label>
<div class="col-sm-7">
<div>
<input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." />
</div>
</div>
</div>


<div class="form-group">
<div class="text-center">
<button type="button" (click)="upload()">Upload</button>
</div>
</div>
</form>

组件.ts

     myfile={
"name":"Mubashshir",
"image":''
}

fileChangeEvent(fileInput: any){
this.myfile.image = fileInput.target.files;
}

upload(){
this.base_path_service.PostRequest('http://128.199.190.109/api/school/schoolDetail/',this.myfile)
.subscribe(
data => {
console.log("data submitted");
},
err => console.log(err),
() =>{
console.log('Authentication Complete');

}
);
}

最佳答案

事实上,Http 类目前不支持。

您需要利用底层 XHR 对象来做到这一点:

import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class UploadService {
constructor () {
this.progress$ = Observable.create(observer => {
this.progressObserver = observer
}).share();
}

private makeFileRequest (url: string, params: string[], files: File[]): Observable {
return Observable.create(observer => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();

for (let i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}

xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
observer.next(JSON.parse(xhr.response));
observer.complete();
} else {
observer.error(xhr.response);
}
}
};

xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);

this.progressObserver.next(this.progress);
};

xhr.open('POST', url, true);
xhr.send(formData);
});
}
}

有关详细信息,请参阅此插件:https://plnkr.co/edit/ozZqbxIorjQW15BrDFrg?p=info .

在 Angular 仓库中有一个问题和一个待处理的 PR:

关于file-upload - Angular2上传文件的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35985347/

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