1 简单写下html
<input id="upload" name="fileSelect" type="file"
accept=".xlsx,.xls" (change)="onFileSelect($event)"/>选择文件
<button type="button" (click)="onSubmit()">提交</button>
2 component.ts
onFileSelect(event: any){
if(event.target.files.length == 1){
this.fileName = event.target.value
this.file = event.target.files.item(0)
}else{
console("请选择文件")
return
}
}
onSubmit(){
this.service.uploadFile(this.file).then(res=>{
console.log(res)
}).catch(err=>{console.log(err)})
}
3 service.ts
注:this.httpRequest是自己封装好的http请求
uploadFile(file: any){
const formData: FormData = new FormData()
formData.append("file", file, file.name)
let params={method: "post", url: "/upload", data: formData}
return this.httpRequest.doRequest(params)
}
1-3写完前端需要的
后端用python写的,用的pecan框架
4 controller.py
@expose()
def upload(self):
try:
data = request.POST["file"].file.read()
full_path = "you_path"
with open(full_path, 'wb+') as f:
f.write(data)
return Response("msg",200)
except Exception as e:
return Response("msg",500)
对比常用的取文件流的方式
file = request.FILES.get("file")
with open(full_path, 'wb') as f:
for chunk in file.chunks():
f.write(chunk)