最近遇到一个需求,前端需要将Excel传到后端去解析,写个Demo记录一下
首先用http传文件的话要用FormData的格式
上传按钮代码
<input #inputFile id="file" accept=".xlsx" type="file" (change)="uploadedFile($event)" multiple="false" />
{{ 'HOME.UPLOADEXCEL'| translate }} //中英文翻译
调用uploadedFile()
import { TssDataService } from '@commonService/basedata/tss-data.service';
constructor(
private TssDataService: TssDataService,
) {
}
uploadedFile = (event: any) => {
const file=event.target.files[0]
//将得到的文件进行实例化,处理成FormData所需格式
const renameFile = new File([file], file.name, { type: file.type });
const form :FormData = new FormData();
form.append('file',renameFile)
this.TssDataService.uploadDataExcel(form).then((data:[])=>{
console.log(data)
)
};
向后端请求
uploadDataExcel(form: FormData):Promise<any>{
const params = {
url: '/tss/upload_excel_data',
data:form
}
return this.httpRequest.Post(params)
}