我创建一个组件编辑一个模型并上传图像。
this is edit.component.html
<form (ngSubmit)="onSubmit()" #heroForm="ngForm">
<div class="form-group">
<table *ngIf="movie">
<tr>
<td>Title</td>
<td>
<input type="text" class="form-control" ngModel="{{movie.id}}" name="id" />
<input type="text" class="form-control ng-untouched ng-pristine ng-valid"
required
[(ngModel)]="movie.title" name="title" #title="ngModel" />
<div [hidden]="title.valid || title.pristine"
class="alert alert-danger">
Name is required
</div>
</td>
</tr>
<tr>
<td>Price</td>
<td><input type="number" class="form-control" [(ngModel)]="movie.price" name="price" /></td>
</tr>
<tr>
<td>Rating</td>
<td><input type="text" class="form-control" [(ngModel)]="movie.rating" name="rating" /></td>
</tr>
<tr>
<td>Genre</td>
<td><input type="text" class="form-control" [(ngModel)]="movie.genre" name="genre"/></td>
</tr>
<tr>
<td>Image</td>
<td>
<img [src]="imgURL" height="100" *ngIf="imgURL">
<input type="file" id="file" (change)="handleFileInput($event.target.files)" >
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" [disabled]="!heroForm.form.valid" (click)="Update()" value="Update" /></td>
</tr>
</table>
</div>
</form>
this is edit.component.ts
export class EditMovieComponent {
constructor(private MoviesService: MoviesService, private route: ActivatedRoute) { }
movie: any;
fileToUpload: File = null;
imgURL: any;
ngOnInit(): void {
var id = this.route.snapshot.paramMap.get('id');
this.getdata(id);
this.imgURL ="assets/images/" + id + ".png";
}
getdata(id) {
this.MoviesService.getDataItem(id).subscribe((data: any) => {
this.movie = data;
})
}
Update() {
this.MoviesService.putData(this.movie.id, this.movie).subscribe((data: any[]) => {
//this.data = data;
if (data == null)
alert("OK");
else
alert("Error");
})
}
handleFileInput(files: FileList) {
//this.fileToUpload = files.item(0);
var reader = new FileReader();
reader.readAsDataURL(files.item(0));
reader.onload = (_event) => {
this.imgURL = reader.result;
}
}
}
这是电影服务:
export class MoviesService {
constructor(private http: HttpClient) { }
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
getData() {
return this.http.get('/api/Movies'); //https://localhost:44352/ webapi host url
}
getDataItem(id) {
return this.http.get('/api/Movies/'+id);
}
putData(id, formData) {
return this.http.put('/api/Movies/' + id, formData);
}
}
这是控制器:
[HttpPut("{id}")]
public async Task<IActionResult> PutMovie(int id, Movie movie)
{
if (id != movie.Id)
{
return BadRequest();
}
_context.Entry(movie).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!MovieExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
这是模型类:
public class Movie
{
[Key]
public int? Id { get; set; }
public string Title { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
public string Rating { get; set; }
}
我想在放置模型数据时上传图像。
如何将模型与图像附加在一起?