【问题标题】:How can i upload image from angular 4 to Web API?如何将 Angular 4 中的图像上传到 Web API?
【发布时间】:2018-06-30 04:15:04
【问题描述】:

我想从 Angular 4 上传图片。在 WebApiController 中调用控制器方法并处理上传图片。请帮帮我!

我的组件 process.ts :

  onUpload(file): void{
    let fileList = FileList = file;
    if(fileList.length > 0){
      let file: File = fileList[0];
      let formData: FormData = new FormData();
      formData.append('uploadFile',file, file.name);
      this.catalogService.uploadFile(formData)
      .subscribe(data => {
        this.toastr.success('Ipload Image Successfully', 'Catalog Book');
      })
    }
  }

我的服务.ts

  uploadFile(form: any){
    var headerOptions = new Headers({'Content-Type':'application/json'});
    var requestOptions = new RequestOptions({method: RequestMethod.Post, headers: headerOptions});
    return this.http.post('http://localhost:20952/api/UploadImage/',form,requestOptions).map(x=>x.json());
  }

来自 Web API 的控制器处理

// POST: api/UploadImage
[HttpPost]
public IHttpActionResult GetCatalog(Guid id)
{
    try
    {
        HttpResponseMessage response = new HttpResponseMessage();
        var httpRequest = HttpContext.Current.Request;

        if (httpRequest.Files.Count > 0)
        {
            foreach (string file in httpRequest.Files)
            {
                var postedFile = httpRequest.Files[file];
                string fileName = id + "jpg";
                var filePath = HttpContext.Current.Server.MapPath("~/Data/" + fileName);
                postedFile.SaveAs(filePath);
            }
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }

    return Ok();
}

【问题讨论】:

  • 现在有什么问题?
  • 无法将“文件上传”传输到控制器 Web API
  • 你能调用 api 吗?你没有将任何 Guid 传递给 api,而且路线也不同于你在 angular 中使用的路线
  • 在api方法之前使用[Route("api/UploadImage/"]并传递guid
  • 我无法想象将“文件上传”传输到 Web api 控制器的方式。

标签: c# angular asp.net-core-webapi


【解决方案1】:

这样我在项目中实现了上传图片到web API。

我为谁担心。

        const formData: FormData = new FormData();
        formData.append('Image', image, image.name);
        formData.append('ComponentId', componentId);
        return this.http.post('/api/dashboard/UploadImage', formData);

一步一步

[HttpPost]
[Route("api/dashboard/UploadImage")]
public HttpResponseMessage UploadImage()
        {
            string imageName = null;
            var httpRequest = HttpContext.Current.Request;
            //Upload Image
            var postedFile = httpRequest.Files["Image"];
            //Create custom filename
            if (postedFile != null)
            {
                imageName = new String(Path.GetFileNameWithoutExtension(postedFile.FileName).Take(10).ToArray()).Replace(" ", "-");
                imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile.FileName);
                var filePath = HttpContext.Current.Server.MapPath("~/Images/" + imageName);
                postedFile.SaveAs(filePath);
            }
}

HTML 表单

<form #imageForm=ngForm (ngSubmit)="OnSubmit(Image)">

                    <img [src]="imageUrl" class="imgArea">
                    <div class="image-upload">
                        <label for="file-input">
                            <img src="upload.jpg" />
                        </label>

                        <input id="file-input" #Image type="file" (change)="handleFileInput($event.target.files)"/>
                        <button type="submit" class="btn-large btn-submit" [disabled]="Image.value=='' || !imageForm.valid"><i class="material-icons">save</i></button>
                    </div>
                </form>

使用 API 的 TS 文件

OnSubmit(Image) {
    this.dashboardService.uploadImage(this.componentId, this.fileToUpload).subscribe(
      data => {
        console.log('done');
        Image.value = null;
        this.imageUrl = "/assets/img/logo.png";
      }
    );
  }

服务 TS

uploadImage(componentId, image) {
        const formData: FormData = new FormData();
        formData.append('Image', image, image.name);
        formData.append('ComponentId', componentId);
        return this.http.post('/api/dashboard/UploadImage', formData);
    }

【讨论】:

    猜你喜欢
    • 2018-07-22
    • 2020-03-15
    • 2021-12-25
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 2018-03-12
    • 2019-08-07
    • 2015-11-24
    相关资源
    最近更新 更多