问题描述
在将文件Blob与我的表单上载到同一数据库时遇到问题。
有我的表格
this.accForm = this.formBuilder.group({
team_leader: ['',Validators.required],hotel_name: ['',address: ['',report_person: ['',room: ['',description: ['',incident_person: ['',damage_notification: ['',damage_photo: ['',photo: ['',comments: ['',check_in: ['',[Validators.required,Validators.pattern(/^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$/)]],check_out: ['',incident_date: ['',},{
});
在我的html输入中,我正在获取文件
<input type="file" class="form-control" id="damage_photo"
(change)="selectFile($event)">
还有我选择文件并上传的功能
selectFile(event) {
this.selectedFiles = event.target.files;
}
get f() { return this.accForm.controls; }
onSubmit() {
this.currentFileUpload = this.selectedFiles.item(0);
//Tried also something like
this.accForm.value.photo = this.selectedFiles.item(0);
this.submitted = true;
if (this.accForm.invalid) {
return;
}
this.accidentFormService.saveAccidentForm(this.accForm.value).subscribe(
res => {
console.log(res);
},err => console.error(err)
);
this.selectedFiles = undefined;
}
还有我要上传的服务
saveAccidentForm(accidentForm: AccidentForm): Observable<HttpEvent<{}>> {
const formdata: FormData = new FormData();
const req = new HttpRequest('POST','http://localhost:8080/accident-form',accidentForm,{
});
return this.http.request(req);
}
如果我只想上传文件,我的服务看起来就像
pushFileToStorageAccidentForm(file: File): Observable<HttpEvent<{}>> {
const formdata: FormData = new FormData();
formdata.append('file',file);
const req = new HttpRequest('POST',formdata,{
reportProgress: true,responseType: 'text'
});
return this.http.request(req);
}
它工作正常,但是如何同时发送表单和文件Blob?
解决方法
您可以将更多属性附加到formdata。在这种情况下,formform.append('data',this.accForm.value)可能有效! :D
,onFileChanged(input) {
let data='';
var reader;
if (input.srcElement.files[0] && (input.srcElement.value.endsWith('jpg') || input.srcElement.value.endsWith('png'))) {
reader = new FileReader();
this.SpecialImagePassing= input.srcElement.files[0] as File;//as a file important
reader.onload = function(e) {
data=e.target.result;
}
reader.readAsDataURL(input.srcElement.files[0]);
}
}
这是获取blob的一种方式,但我强烈建议您使用multer.js进行文件上传和保存,因为您不能在不使用角度清理功能的情况下分配blob,并且有时db会拒绝blob的大小过大>