如何将javascript类型的File绑定到包含HttpFile的Nancy模型?

时间:2017-10-17 17:06:19

标签: javascript c# typescript nancy

我正在尝试将包含File in typescript的put请求绑定到Nancy的HttpFile。请求始终将C#中的HttpFile设置为null。有没有办法做到这一点?

@Injectable()
export class FileUploadService {

  @Output() progress: EventEmitter<number> = new EventEmitter<number>();

  /**
   * uploads a file to the service and returns the document's id
   */

  public upload(req: IUploadRequest): Observable<number> {

let promise = new Promise((resolve: any, reject: any) => {

  let xhr: XMLHttpRequest = new XMLHttpRequest();

  xhr.upload.onprogress = (event: any) => {
    let progress = Math.round(event.lengthComputable ? event.loaded * 100 / event.total : 0);
    this.progress.emit(progress);
  };

  xhr.onload = () => {
    let json = JSON.parse(xhr.response);
    resolve(<number>json.documentId);
  };

  xhr.onerror = () => {
    reject(xhr.response);
  };

  xhr.onabort = () => {
    reject(xhr.response);
  };

  xhr.open("PUT", `${environment.API_ROOT}/document`, true);
  xhr.setRequestHeader(environment.AUTH_HEADER_NAME, getToken());
  let formData: FormData = new FormData();
  formData.append("file", <File>req.file, req.file.name);

  formData.append("description", req.description);
  formData.append("chapterId", req.chapterId.toString());
  xhr.send(formData);
});

return Observable.fromPromise(promise);
  }
}

export class IUploadRequest {
  public file: File;
  public description: string;
  public chapterId: number;
}

我试图绑定的模型......

    public class FileUploadRequest
{
    public long ContentSize { get; set; }
    public HttpFile File { get; set; }
    public string  Description { get; set; }
    public int ChapterId { get; set; }
}

在C#API中......

 var request = this.Bind<FileUploadRequest>();

我做错了什么? “file”在C#中总是以null返回。

1 个答案:

答案 0 :(得分:0)

只是一个FYI ...我通过进入请求本身并在Request.File中获取文件来修复此问题。