繁体   English   中英

角2 formdata空

[英]angular 2 formdata empty

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

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

myComponent的

let fp = new fileUploadParametre();
let formData: FormData = new FormData();
var file; 

if ($('#fileinput')[0] != undefined) {
  if ($('#fileinput')[0].files.length > 0) {
    file = $('#fileinput')[0].files[0];
    formData.append('uploadingFile', file);
    //fp.fileName = file.name;
    console.log(formData);
  }
  formData.append('siparisid', this.siparis.siparisid);
  formData.append('dokumantipi',this.form.controls.belgeTipiFormController.value);
  formData.append('aciklama',this.form.controls.aciklamaFormController.value);

  this.fileUploadService.kaydet(
    formData
  )
    .subscribe(result => {
      console.log(result);
      if (result === true) {
        this.errorMessages = [];
        this.dialogRef.close(true)
      }
      else
        this.errorMessages = ['Kayıt Yapılamadı'];
    },
    err => {
      if (err.status == 0) {
        this.errorMessages = ['Bağlantı hatası! sunucuya erişilemedi.'];
      }
      else if (err.status == 404) {
        this.errorMessages = ['Bağlantı hatası! sunucuya erişilemedi.'];
      }
      else if (err.status == 401) {
        this.errorMessages = ['Yetki Hatası.'];
      }


      else if (err.status == 400) {
        let errBody = JSON.parse(err._body);
        if (errBody
          && errBody['error'] == 'invalid_grant')
          this.errorMessages = ['Oturum Açılamadı Geçersiz Kullanıcı veya Şifre'];
        else
          this.errorMessages = [errBody.message];
      }
      else
        this.errorMessages = [err.statusTest]

    }
    );
}


 **my Service**

 public kaydet(
  formData: FormData
 ): Observable<any> {

let postFiles = {
  formData: formData
};

return this.http.post(
  this.apiUrl + '/dokumanlar/ResimKaydet',
  JSON.stringify(postFiles)
)
  .map(res => res.json());
}

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

要将image(avatar)发送到服务器或web 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) => { } ); } } 

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

formData.append(name, fileValue, fileName)

我使用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. 组件

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

    }}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM