如何使用附加图像更新模型?

2023-12-11

我创建一个组件编辑一个模型并上传图像。

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; }       
 
    }

我想在放置模型数据时上传图像。

如何将模型与图像附加在一起?


我想在放置模型数据时上传图像。如何将模型与图像附加在一起?

根据您的代码,我们可以发现您使用FileReader.readAsDataURL()获取所选图像的 Base64 编码字符串。

如果您想在电影数据中包含 base64 编码的图像,并将其发布到后端 API 服务,您可以将以下属性添加到您的Movie模型类。

public string imgURL { get; set; } 

测试结果

enter image description here

此外,如果您想上传文件并将其直接保存在网络服务器上的文件系统中。您可以通过修改如下代码来实现它。

将此属性添加到 Movie 类

public IFormFile Img { get; set; }

修改 Angular 客户端代码以通过 formdata 使用所选文件发布数据

fileToUpload: FileList = null;

//...


handleFileInput(files: FileList) {
  this.fileToUpload = files;

  //...
}

//...

const formData = new FormData();
formData.append("id", this.movie.id);
formData.append("title", this.movie.title);
formData.append("genre", this.movie.genre);
formData.append("price", this.movie.price);
formData.append("rating", this.movie.rating);
formData.append("img", this.fileToUpload.item(0));

this.http.put("https://xxx/xxx/xxx/1", formData).subscribe( //....

测试结果

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用附加图像更新模型? 的相关文章