Angular File Upload

后端 未结 12 2153
名媛妹妹
名媛妹妹 2020-11-22 10:04

I\'m a beginner with Angular, I want to know how to create Angular 5 File upload part, I\'m trying to find any tutorial or doc, but I don\'t see anything a

12条回答
  •  生来不讨喜
    2020-11-22 10:55

    This way I implement upload file to web API in project.

    I share for whom concern.

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

    Step by step

    ASP.NET Web API

    [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

    TS file to use API

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

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

提交回复
热议问题