我正在学习教程 here ,关于如何使用 Angular2 上传文件。然而,当我尝试将代码实现到我的项目中时,我的控制台中的结果只是页面 html 内容,而不是我认为通过我的后端( asp.net core )上的 POST 请求发送的 JSON 响应。在网络选项卡下,它似乎将 POST 发送到正确的地址,所以我不知道为什么我收到的是 html 文档而不是响应数据。有人知道为什么吗?
上传.html
<h2>Upload</h2>
<input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." />
<button type="button" (click)="upload()">Upload</button>
upload.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 ? ");
}
最佳答案
首先,您似乎是通过创建表单数据从 Angular 部分直接完成此操作。我在 asp.net 中的 POST 请求上正确获取文件时遇到了一些类似的问题。所以我解决这个问题的方法是解析Request中的内容。
首先创建一个空方法,这很重要,否则你最终会得到 404。接下来从 Request 对象中读取文件:
[HttpPost]
public IActionResult uploadFile()
{
var files = Request.Files;
if (Request.Form[0] == null || files[0] == null || files[0].ContentLength < 1)
{
// TODO log
Response.StatusCode = 400;
return Json("Please provide a file");
}
// TODO parse the file(s) as you like :)
foreach (HttpPostedFile file in files)
{
file.SaveAs(file.FileName);
}
}
[针对 asp.net core 进行了更新]
更改了asp.net core中的Request对象,现在表单数据位于:
Request.Form.Files;
关于javascript - 使用 Angular2 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39663768/