繁体   English   中英

Angular:无法使用 FormData 在 web API 上上传文件

[英]Angular : Unable to upload file on web API using FormData

当我单步执行代码时,我的 formData 为空,当它到达 API 端时,参数 pFileToUpload 的值为 null

第 1 步:HTML

 <div class="form-group">
  <input type="file" id="file"(change)="handleFileInput($event.target.files)">
 </div>

第二步:TypeScript Component.ts

  handleFileInput(files: FileList) {
    this.mfileToUpload = files.item(0);
    this.uploadFile();
}

async uploadFile() {

  // tslint:disable-next-line:max-line-length
  const savedAttach = await  this.UploadService.postAttachmentFile(this.Params.AccountID, this.Params.ContactID, this.Params.ReservationID , this.mfileToUpload).toPromise();
}

第 3 步:UploadServiceServices.ts

 postAttachmentFile(pAccountID: number, pContactID: number, pReservationID: number,  pFileToUpload: File) {
    const formData: FormData = new FormData();
    formData.append('fileKey', pFileToUpload, pFileToUpload.name);

    return this.http.post<boolean>(URL +
    '/uploadFile/PostAttachmentFile' +
    '?pAccountID=' + pAccountID +
    '&pContactID=' + pContactID +
    '&pReservationID=' + pReservationID +
    '&pActiveUserID=' + this.getUserID(),
    formData
  ).pipe(
    map(response => {
      return response;
    })
  );
  }

第 4 步:将其发布到 API 端

    [Route("uploadFile/PostAttachmentFile")]
    [HttpPost]

        public bool PostAttachmentFile(int pAccountID, int pContactID, int pReservationID, int pActiveUserID, HttpPostedFileBase pFileToUpload)
        {
            return getWebService().PostAttachmentFile(pAccountID, pContactID, pReservationID, pActiveUserID,  pFileToUpload);
        }

要解决此问题:删除 HttpPostedFileBase 参数并在 PostAttachmentFile function 中执行以下操作:

var httpRequest = HttpContext.Current.Request;
            
            var postedFile = httpRequest.Files["fileKey"];

            PostedFile file = new PostedFile();
            file.ContentLength = postedFile.ContentLength;
            file.ContentType = postedFile.ContentType;
            file.FileName = postedFile.FileName;

            file.Data = new byte[file.ContentLength];
            postedFile.InputStream.Read(file.Data, 0, file.ContentLength);

并创建一个 class


public class PostedFile
        {
            public int ContentLength { get; set; }
            public string ContentType { get; set; }
            public string FileName { get; set; }
            public byte[] Data { get; set; }
        }

暂无
暂无

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

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