gpt4 book ai didi

使用 WebApi 上传 Angular2 文件

转载 作者:太空狗 更新时间:2023-10-29 18:25:47 24 4
gpt4 key购买 nike

Angular2 我想上传文件并将文件保存在服务器文件夹中,但我无法获取 HttpContext.Current.Request.Files,它始终为空。我的代码
-UploadService.ts

 postFileUpLoad(url: string, data: any): any {
let headers = new Headers();
if (localStorage.getItem('localStorage') != null) {
headers.append('Content-Type', 'multipart/form-data')
headers.append('Authorization', "Bearer " + JSON.parse(localStorage.getItem('localStorage')).idToken);
}
this.slimLoadingBarService.startLoading();
return this.http.post(url, data, {
headers: headers
})
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}

-上传文件组件

onChange(event) {
let fileList: FileList = event.target.files;
if (fileList.length > 0) {
let file: File = fileList[0];
let formData: FormData = new FormData();
formData.append('uploadFile', file, file.name);
this.httpService.postFileUpLoad('http://localhost:3000/api/uploadFile', formData);
}}


- HTML

<input type="file" id="btnUpload" value="Upload" name="FileUpLoad" (change)="onChange($event)" class="upload" />

- API服务上传

[HttpPost]
[Route("uploadFile")]
public HttpResponseMessage UploadJsonFile()
{
HttpResponseMessage response = new HttpResponseMessage();
var abc = Request.Properties.Values;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/UploadFile/" + postedFile.FileName);
postedFile.SaveAs(filePath);
}
}
return response;
}

请帮帮我,非常感谢!

最佳答案

您必须删除此行。

   headers.append('Content-Type', 'multipart/form-data')

然后它会起作用。

关于使用 WebApi 上传 Angular2 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42268413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com