角2 formdata空

时间:2017-12-05 15:05:32

标签: angular form-data

我无法将数据传递给FormData。我搜索了。但我无法理解。请你帮助我好吗。   我的目标;使用Web API保存图像文件2.我没有写更多wep api 2.

我找不到解决方案。有没有其他方式使用它?

myComponent的

\b\d{4}\b

formData = formData {}>>以这种方式是空的。

2 个答案:

答案 0 :(得分:4)

要将image(avatar)发送到服务器或网络API,您可以使用FormData,如果您想要遵循此目的,请逐步完成以下工作:

  1. 在html文件中使用#avatar访问组件中的ElementRef

    <form (ngSubmit)="onSubmit()">
        <input type="file" accept=".png, .jpg, .jpeg" #avatar>
    </form>
    
    1. 创建component并使用sending image到服务器;

      import {Component} from '@angular/core';
      import {ElementRef} from '@angular/core';
      import {ViewChild} from '@angular/core';
      
      import {HttpClient} from '@angular/common/http';
      import {HttpParams} from '@angular/common/http';
      import {HttpHeaders} from '@angular/common/http';
      
      @Component({
          selector: 'app-avatar',
          templateUrl: './avatar.component.html',
          styleUrls: ['./avatar.component.css']
      })
      export class AvatarComponent {
          @ViewChild('avatar') avatar: ElementRef;
      
          constructor(private http: HttpClient) { }
      
          onSubmit() {      
              const formData = new FormData();
              formData.append('avatar', 
                              this.avatar.nativeElement.files[0], 
                              this.avatar.nativeElement.files[0].name);
      
              const headers = new HttpHeaders();
              headers.append('Content-Type', 'multipart/form-data');
              headers.append('Accept', 'application/json');
              this.http.post('api/upload', formData, {headers: headers})
                  .subscribe(
                      (response) => {
                      },
                      (error) => {
                      }                   
                   );
           }
      
      }
      
    2.   

      注意将文件添加到FormData,如下面的参数方法

           

      formData.append(name, fileValue, fileName)

答案 1 :(得分:0)

我通过FormData传递数据 在我的情况下我使用了formData。 set (name,fileValue,fileName) 而不是formData。append(name,fileValue,fileName) 请参阅LINK

  1. <强> HTML

    <input type="file"
       name="fileItem"
       id="fileItem"  
       (change)="handleFileInput($event.target.files)"/>
    
  2. 2的元器件

    handleFileInput(files: FileList) {
        this.fileToUpload = files.item(0);
        this.uploadFileToServer();
      }
    uploadFileToServer() {
    this.fileUploadService.UploadFile(this.fileToUpload).subscribe(data => {
    }, error => {
      console.log(error);
    });}
    

    3的服务

    UploadFile(fileToUpload: File): Observable<boolean> {
    const endpoint = 'api/image/upload';
    var formData = new FormData();
    formData.set('file', fileToUpload);
    return this._http
      .post(endpoint, formData)
      .map(() => { return true; })
      .catch((e) => this.handleError(e));}
    

    4。 服务器

    [Route("upload")]
    
    public IHttpActionResult UploadImage()
    {
        try
        {
    
            var httpRequest = HttpContext.Current.Request;
    
            foreach (string file in httpRequest.Files)
            {
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
    
                var postedFile = httpRequest.Files[file];
                if (postedFile != null && postedFile.ContentLength > 0)
                {
    
                    int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB  
                    IList<string> AllowedFileExtensions = new List<string> { ".jpg", ".gif", ".png" };
                    var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
                    var extension = ext.ToLower();
                    if (!AllowedFileExtensions.Contains(extension))
                    {
    
                        var message = string.Format("Please Upload image of type .jpg,.gif,.png.");
    
                        dict.Add("error", message);
                        return Ok();
                    }
                    else if (postedFile.ContentLength > MaxContentLength)
                    {
                        var message = string.Format("Please Upload a file upto 1 mb.");
                        dict.Add("error", message);
                        return Ok();
                    }
                    else
                    {
                       var filePath = HttpContext.Current.Server.MapPath("~/Userimage/" + postedFile.FileName + extension);
                        postedFile.SaveAs(filePath);
                    }
                }
                var message1 = string.Format("Image Updated Successfully.");
                return Ok();
            }
            var res = string.Format("Please Upload a image.");
            dict.Add("error", res);
            return Ok();
        }
        catch (Exception ex)
        {
            var res = string.Format("some Message");
            dict.Add("error", res);
            return Ok();
    
        }}