0

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

第 1 步:HTML

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

第 2 步:TypeScript 组件 .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);
        }
4

1 回答 1

0

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

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

并创建一个类


public class PostedFile
        {
            public int ContentLength { get; set; }
            public string ContentType { get; set; }
            public string FileName { get; set; }
            public byte[] Data { get; set; }
        }
于 2020-07-27T08:58:28.027 回答