在模板中创建文件输入
<input type="file" #fileInput />
<button (click)="uploadFile();">Upload</button>
然后前往您的组件
@ViewChild('fileInput') fileInput;
// inject httpclient from @angular/common/http
...
public uploadFile(): void {
if (this.fileInput.files.length === 0) {
return; // maybe needs more checking
}
const formData = new FormData();
formData.append('file', this.fileInput.files[0]);
this.http.post('http://my-url/api/my-endpoint', formData).subscibre(...); // the usual
}
现在在API中创建这样的端点
[HttpPost]
// the name here must be file for the parameter, bc you declared it as such in your formdata
public IActionResult UploadFile([FromBody] IFormFile file)
{
// depending on what you wanna do you can either create and store it in the filesystem or copy the file into a byte array and store it in your db
}
如果您明确了要保存文件的位置,我可以展开C代码。但一般来说,这是您从前端接收文件的方式,也就是从后端接收文件的方式。