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;
}
请帮助我,非常感谢!
答案 0 :(得分:3)
您必须删除此行。
headers.append('Content-Type', 'multipart/form-data')
之后它会起作用。
答案 1 :(得分:0)
更改您的API方法,如下所示:
[HttpPost]
[Route("uploadFile")]
public HttpResponseMessage UploadJsonFile()
{
HttpResponseMessage response = new HttpResponseMessage();
var abc = Request.Properties.Values;
var httpRequest = HttpContext.Current.Request;
var fileCount = httpRequest.Files.Count;
if (httpRequest.Files.Count > 0)
{
for (int i=0; i< fileCount ; i++)
{
var postedFile = httpRequest.Files[i];
var filePath = HttpContext.Current.Server.MapPath("~/UploadFile/" + postedFile.FileName);
postedFile.SaveAs(filePath);
}
}
return response;
}
您将在“postingFile”中获取该文件。