[英]Angular 4. File upload
我使用Angular 4,我有這段代碼。
uploadPhoto(file: File):Promise<any> {
var formData = new FormData();
formData.append('req', file);
return this.http.post(`${this.urlApi}/uploadphoto`, formData, {
withCredentials: false,
body: formData,
})
.toPromise()
.catch(this.handleError); }
然后,我在Java Spring上調試程序。 我在調試面板中只有參數“ req”,但沒有多部分文件。 我將標頭設置為“ multipart / form-data”和“ undefined”。 我設置了“ formData.append('req',file [0]);”,此外,我使用了以下代碼:
uploadPhoto2(file:File){
var formData = new FormData();
formData.append('file', file);
var request = new XMLHttpRequest();
request.open('POST', `${this.urlApi}/uploadphoto`);
request.send(formData);
}
我有相同的結果。 在chrome控制台中,我看到:Content-Type:multipart / form-data; 邊界= ---- WebKitFormBoundarycE8MNSpWUCwCDLLB
這段代碼對我來說很好用:
HTML代碼:(用於圖片)
<div class="form-group">
<label for="usr">Upload your new photo(Optional):</label> <input type="file" accept=".jpg,.png,.jpeg" (change)="attachFile($event)">
<br>
<img src="{{imageSrc}} | defaultPipe " height="250" weight="250" alt="Image preview..." />
</div>
角碼:
attachFile(event) : void {
var reader = new FileReader();
let _self = this;
reader.onload = function(e) {
_self.imageSrc = reader.result;
console.log(_self.imageSrc);
};
reader.readAsDataURL(event.target.files[0]);
}
注意:在方法中,必須為此操作符定義一個局部變量才能在函數中使用它。 在imageSrc中,您有base64個字節的文件數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.