【发布时间】:2019-11-24 14:25:51
【问题描述】:
你好,有一个客户端-服务器项目,一个客户端在机库上,一个服务器在树皮上。在服务器端,文件下载代码:
[HttpPost("[action]/{formData}"), Route("addfile")]
public async Task AddFile(IFormFile formData)
{
string path = "/Files/" + formData.FileName;
using (var fileStream = new FileStream(_appEnvironment.WebRootPath + path, FileMode.Create))
{
await formData.CopyToAsync(fileStream);
}
FileModel file = new FileModel { Name = formData.FileName, Path = path };
db.Files.Add(file);
db.SaveChanges();
}
在客户端:组件:
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpEventType } from '@angular/common/http';
@Component({
selector: 'add-file',
templateUrl: './add-files.component.html',
})
export class AddFilesComponent implements OnInit {
fileData: File = null;
previewUrl: any = null;
fileUploadProgress: string = null;
uploadedFilePath: string = null;
constructor(private http: HttpClient) { }
ngOnInit() {
}
fileProgress(fileInput: any) {
this.fileData = <File>fileInput.target.files[0];
this.preview();
}
preview() {
// Show preview
var mimeType = this.fileData.type;
if (mimeType.match(/image\/*/) == null) {
return;
}
var reader = new FileReader();
reader.readAsDataURL(this.fileData);
reader.onload = (_event) => {
this.previewUrl = reader.result;
}
}
onSubmit() {
let formData = new FormData();
formData.append('files', this.fileData);
this.fileUploadProgress = '0%';
this.http.post('http://localhost:5000/api/file/addfile', formData, {
reportProgress: true,
observe: 'events'
})
.subscribe(events => {
if (events.type === HttpEventType.UploadProgress) {
this.fileUploadProgress = Math.round(events.loaded / events.total * 100) + '%';
console.log(this.fileUploadProgress);
} else if (events.type === HttpEventType.Response) {
this.fileUploadProgress = '';
console.log(events.body);
alert('SUCCESS !!');
}
})
}
}
HTML:
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<h3>Choose File</h3>
<div class="form-group">
<input type="file" name="image" (change)="fileProgress($event)" />
</div>
<div *ngIf="fileUploadProgress">
Upload progress: {{ fileUploadProgress }}
</div>
<div class="image-preview mb-3" *ngIf="previewUrl">
<img [src]="previewUrl" height="300" />
</div>
<div class="mb-3" *ngIf="uploadedFilePath">
{{uploadedFilePath}}
</div>
<div class="form-group">
<button class="btn btn-primary" (click)="onSubmit()">Submit</button>
</div>
</div>
</div>
</div>
注意:如果你只在皮质中实现一切,那么一切正常,文件被加载,所以一切都与代码一致。问题是文件不是从服务端来的,它在客户端传了一个断点,文件发送出去了,我在服务端放了一个断点,我用新的方式启动一切,有一个反应,就是,客户端在服务端启动方法,但是我看到IFormFile formData为null,表示没有什么可保存的。。我觉得我在小事情上犯了错误,请戳哪里...
【问题讨论】:
标签: c# asp.net angular asp.net-core