在组件中增加以下代码:
import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
fileData: File = null;
@ViewChild(NgForm) form: NgForm;
constructor(private http: HttpClient) { }
onFileSelect(event) {
if (event.target.files.length > 0) {
const file = event.target.files[0];
this.fileData = file;
}
}
onSubmit() {
const formData = new FormData();
formData.append('file', this.fileData);
this.http.post('/api/upload', formData)
.subscribe(res => {
console.log(res);
this.form.reset();
});
}
}
另外,需要在上传文件的API中,添加Content-Disposition头部,如下所示:
Content-Disposition: attachment;filename="your_file_name.jpg"
这样就可以成功上传视频文件,并且video_url将会正确显示文件。
上一篇:Angular上传进度报告不正确
下一篇:Angular上传图片到服务器