如何通过角度将照片上传到Web API并将该照片和其他值添加到类中的新对象

时间:2019-05-18 15:40:05

标签: c# angular

因此,我正在制作一个带有angular和.NET API的应用程序。我希望人们上传带有一些文本的图像(例如,名称,城市等)。我已经找到了一种将图像从有角度的前端上传到后端的方法。问题是,当我将图像选择器放在具有其他一些输入字段的表单中时,会收到错误请求。为了使事情更清楚,请查看代码。谢谢您的帮助。

在下面的链接上,您可以找到我如何存储上传的图像的照片。因此,如果上传成功,则必须有一种方法将这些照片实际添加到其他值中并生成一张证件。我只是不知道我在做什么错。 https://imgur.com/ROk78EL

在这2个链接上,您可以看到我想要输入什么,然后使用该输入做什么。 https://imgur.com/g6k2VAl(表格)https://imgur.com/FyzmLgh(结果)

这是我的Card类中的卡片构造函数

       {
           Provincie = provincie;
           Postcode = postcode;
           Stad = stad;
           Photo = photo;
           Text = text;
           Likes = likes;
           Moeilijkheidsgraad = moeilijkheidsgraad;
       }

这是我制作新卡的邮政方式:

  [HttpPost]
        public ActionResult<Card> PostCard(CardDTO card)
        {
            Card cardToCreate = new Card() { Provincie = card.Provincie, Postcode = card.Postcode,
                Stad = card.Stad , Text = card.Text, Photo= card.Photo, Likes = card.Likes, Moeilijkheidsgraad = card.Moeilijkheidsgraad};
            _cardRepository.Add(cardToCreate);
            _cardRepository.SaveChanges();

            return CreatedAtAction(nameof(GetCard), new { id = cardToCreate.CardId }, cardToCreate);
        }

这是我的onSubmit(),所以当表单被填写并按下时

  onSubmit() {
    this._cardDataService.uploadFile(this.add.value.image.files);


    this._cardDataService
      .addNewRecipe(new Card(this.add.value.provincie, this.add.value.postcode, this.add.value.stad,
      this.add.value.text,  this.add.value.image.files,  0, this.add.value.moeilijkheidsgraad)).subscribe();
    this.submitted = true;
    // this.add.reset();
    // this.removeImage();
  }

这是我与后端中post方法的连接。

  addNewRecipe(card:Card) {
    return this.http.post(`${environment.apiUrl}/Card`, card.toJSON());
  }

这是我将图像发送到后端的方式

  public uploadFile = (files) => {
    if (files.length === 0) {
      return;
    }

    let fileToUpload = <File>files[0];
    const formData = new FormData();
    formData.append('file', fileToUpload, fileToUpload.name);

    this.http.post(`${environment.apiUrl}/Upload`, formData, {reportProgress: true, observe: 'events'})
      .subscribe(event => {
        if (event.type === HttpEventType.UploadProgress)
          this.progress = Math.round(100 * event.loaded / event.total);
        else if (event.type === HttpEventType.Response) {
          this.message = 'Upload success.';
          this.onUploadFinished.emit(event.body);
        }
      });
    }

这是API上传方法

 [HttpPost, DisableRequestSizeLimit]
        public IActionResult Upload()
        {
            try
            {
                var file = Request.Form.Files[0];
                var folderName = Path.Combine("wwwroot","Resources", "Images");
                var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);

                if (file.Length > 0)
                {
                    var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    var fullPath = Path.Combine(pathToSave, fileName);
                    var dbPath = Path.Combine(folderName, fileName);

                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }

                    return Ok(new { dbPath });
                }
                else
                {
                    return BadRequest();
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, "Internal server error");
            }
        }

1 个答案:

答案 0 :(得分:0)

onSubmit方法上,您首先要上传文件,然后再次使用表单将其发送到服务器,正如您所说的Photo属性是字符串,在后端,因此您将Bad request

  1. 上传照片并成功保存后,让服务器将PhtotPath作为response返回。
  2. 现在将带有表单值的PhtotPath发送到服务器。
onSubmit() {
  // it should be array when you have multiple photos
  let photoPath;
  this._cardDataService.uploadFile(this.add.value.image.files).subscribe(res => {
    // the response from the api should have the photoPath
      photoPath = res.dbPath;
      this._cardDataService.addNewRecipe(
        new Card(this.add.value.provincie, this.add.value.postcode,
         this.add.value.stad, this.add.value.text, photoPath, 0, 
         this.add.value.moeilijkheidsgraad)).subscribe(res => {
              this.submitted = true;
         });

  });
 }