上传图像文件,将图像文件转换为字节数组,然后通过post方法将其发送到后端
我试图使用FileReader()并将其隐藏到数组缓冲区中。但这给了我一个明确的对象。
这是我用来上传图片的按钮。当表单提交后,我正在调用onSubmit函数来发布数据。
<input type="file" style="display: none" accept="image/*" (change)="onFileChanged($event)" #fileInput>
<a mat-raised-button class="btn" (click)="fileInput.click()">Upload Logo</a>
<img class="btn" *ngIf="selectedFile != null" style="width: 30%; height: 3%" src="data:image/jpg;base64,{{selectedFile}}">
<img *ngIf="selectedFile == null" style="display: none">
这是我用来上传图片的功能
onFileChanged(event) {
this.selectedFile = event.target.files[0];
console.log('Selected file before:',this.selectedFile);
let reader = new FileReader();
reader.onload = function(){
let arrayBuffer = this.result;
let bytes = new Uint8Array(arrayBuffer);
console.log(bytes);
}
reader.readAsArrayBuffer(this.selectedFile);
}
这是我的onSubmit函数
onSubmit() {
const data = {};
data['name'] = this.addEntityForm.value.entityCode;
data['description'] = this.addEntityForm.value.entity;
data['displayName'] = this.addEntityForm.value.eDisplayName;
if (this.selectedFile != null){
data['logo'] = this.selectedFile;
console.log('Inside the selectedFile if');
console.log(this.selectedFile);
}
else {
data['logo'] = null;
console.log('Inside the else')
}
data['status'] = 'ACTIVE';
console.log('Posted data :', data);
this.profileServise.addNewEntity(data).subscribe( result => {
if (result) {
this.globalService.updateEntityTable(result);
}
this.openSnackbar('New Entity Created Successfully');
this.matDialogRef.close();
}, error => {
this.openSnackbar('An Error in Creating a New Entity');
});
}
我想将上传的图像作为字节数组发送到后端