如何更新带有图像的模型? [英] How can update a model with images attach?

查看:42
本文介绍了如何更新带有图像的模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是 edit.component.html

 < form(ngSubmit)="onSubmit()";#heroForm ="ngForm">< div class ="form-group">< table * ngIf =电影">< tr>< td>标题</td>< td><输入类型=文本";class ="form-control"ngModel =" {{movie.id}}"name ="id"/><输入类型=文本";class ="form-control ng-untouched ng-pristine ng-valid".必需的[(ngModel)] ="movie.title";名称=标题"#title =" ngModel"/>< div [hidden] =" title.valid ||title.pristine"class ="alert alert-danger">名称为必填项</div></td></tr>< tr>< td>价格</td>< td><输入类型=数字"class ="form-control"[(ngModel)] ="movie.price";名称=价格"/></td></tr>< tr>< td>等级</td>< td><输入类型=文本"class ="form-control"[(ngModel)] ="movie.rating";name =评级"/></td></tr>< tr>< td>类型</td>< td><输入类型=文本"class ="form-control"[(ngModel)] ="movie.genre";名称=流派"//td</tr>< tr>< td>图片</td>< td>< img [src] =" imgURL"高度="100"* ngIf =" imgURL"><输入类型=文件";id ="file"(change)="handleFileInput($ event.target.files)"></td></tr>< tr>< td></td>< td><输入类型=提交"[disabled] =!heroForm.form.valid"(click)="Update()";值=更新";/></td></tr></table></div></form> 

这是 edit.component.ts

 导出类EditMovieComponent {构造函数(私有MoviesService:MoviesService,私有路由:ActivatedRoute){}电影:任何;fileToUpload:File = null;imgURL:任何;ngOnInit():void {var id = this.route.snapshot.paramMap.get('id');this.getdata(id);this.imgURL =资产/图片/"+ id +".png";}getdata(id){this.MoviesService.getDataItem(id).subscribe((data:any)=> {this.movi​​e =数据;})}更新() {this.MoviesService.putData(this.movi​​e.id,this.movi​​e).subscribe((data:any [])=> {//this.data = data;如果(数据==空)警报("OK");别的alert(错误");})}handleFileInput(files:FileList){//this.fileToUpload = files.item(0);var reader = new FileReader();reader.readAsDataURL(files.item(0));reader.onload =(_event)=>{this.imgURL = reader.result;}}} 

这是MovieService:

 导出类MoviesService {构造函数(私有http:HttpClient){}httpOptions = {标头:新的HttpHeaders({'内容类型':'应用程序/json'})}getData(){返回this.http.get('/api/Movies');//https://localhost:44352/webapi主机网址}getDataItem(id){返回this.http.get('/api/Movies/'+ id);}putData(id,formData){返回this.http.put('/api/Movies/'+ id,formData);}} 

这是控制者:

  [HttpPut("{id}"))]公共异步Task< IActionResult>PutMovie(int id,电影电影){如果(id!= movie.Id){返回BadRequest();}_context.Entry(movie).State = EntityState.Modified;尝试{等待_context.SaveChangesAsync();}捕获(DbUpdateConcurrencyException){如果(!MovieExists(id)){返回NotFound();}别的{扔;}}返回NoContent();} 

这是Model类:

 公共课程电影{[钥匙]公共诠释?ID {get;放;}公共字符串Title {get;放;}公共字符串类型{放;}公共十进制价格{放;}公共字符串Rating {get;放;}} 

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

如何放置带有图像的模型?

解决方案

放置模型数据时,我想上传图像.带有图像的模型如何附加?

根据您的代码,我们可以发现您使用

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

将此属性添加到Movie类

  public IFormFile Img {get;放;} 

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

  fileToUpload:FileList = null;//...handleFileInput(files:FileList){this.fileToUpload =文件;//...}//...const formData = new FormData();formData.append("id",this.movi​​e.id);formData.append("title",this.movi​​e.title);formData.append("genre",this.movi​​e.genre);formData.append("price",this.movi​​e.price);formData.append("rating",this.movi​​e.rating);formData.append("img",this.fileToUpload.item(0));this.http.put("https://xxx/xxx/xxx/1",formData).subscribe(//.... 

测试结果

i create a component edit a model has upload imgages.

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

This is MovieService:

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

This is controller:

       [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();
        }

this is Model class:

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

i want upload images when put model data.

How can put model with images attach?

解决方案

i want upload images when put model data. How can put model with images attach?

Based on your code, we can find that you use FileReader.readAsDataURL() to get base64-encoded string of the selected image.

If you'd like to include base64-encoded image within movie data, and post it to backend API service, you can add following property to your Movie model class.

public string imgURL { get; set; } 

Test Result

Besides, if you'd like to upload the file and save it in file system on web server directly. You can achieve it by modifying the code like below.

Add this property to Movie class

public IFormFile Img { get; set; }

Modify Angular client side code to post data with selected file through 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( //....

Test Result

这篇关于如何更新带有图像的模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆