【发布时间】:2017-02-01 11:47:05
【问题描述】:
我正在关注一个教程 here,关于如何使用 Angular2 上传文件。但是,当我尝试将代码实现到我的项目中时,我的控制台中的结果只是页面 html 内容,而不是我假设通过后端(asp.net 核心)上的 POST 请求发送的 JSON 响应。在网络选项卡下,似乎将 POST 发送到正确的地址,所以我不知道为什么我得到一个 html 文档而不是我的响应数据。有谁知道为什么?
上传.html
<h2>Upload</h2>
<input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." />
<button type="button" (click)="upload()">Upload</button>
上传.ts
import * as ng from '@angular/core';
@ng.Component({
selector: 'upload',
template: require('./upload.html')
})
export class Upload {
filesToUpload: Array<File>;
constructor() {
this.filesToUpload = [];
}
upload() {
this.makeFileRequest("http://localhost:5000/api/SampleData/uploadFile", [], this.filesToUpload).then((result) => {
console.log(result);
}, (error) => {
console.error(error);
});
}
fileChangeEvent(fileInput: any){
this.filesToUpload = <Array<File>> fileInput.target.files;
}
makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
return new Promise((resolve, reject) => {
var formData: any = new FormData();
var xhr = new XMLHttpRequest();
for(var i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
}
SampleData.cs
[HttpPost]
public IActionResult uploadFile()
{
var files = Request.Form.Files;
return Json("Working ? ");
}
【问题讨论】:
标签: javascript c# angular xmlhttprequest asp.net-core