我将尝试使用C#中的Web API上传文件。我使用的代码如下:
httpRequest.Files.Count在上传文档时始终为零。
我做错了什么?
mcDocuments.ts文件:
mcDocuments.ts文件:
fileChange(event) {
debugger;
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);
let token = JSON.parse(Cookie.get('currentUser')).token
let headers = new Headers();
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Authorization', 'bearer ' + token);
headers.append('UserName',
JSON.parse(Cookie.get('currentUser')).username);
headers.append('Content-Type', 'multipart/form-data');
let options = new RequestOptions({ headers: headers });
let apiUrl1 = "http://localhost:53732/api/UploadFileApi";
this.http.post(apiUrl1, formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
)
}
window.location.reload();
}
mcDocuments.html文件
<input type="file" id="btnUpload" value="Upload" (change)="fileChange($event)" class="upload" />
web Api
using System.Net.Http;
using System.Web;
using System.Web.Http;
namespace FileUpload_WebAPI_Angular2.Controllers
{
public class UploadFileApiController : ApiController
{
[HttpPost]
public HttpResponseMessage UploadJsonFile()
{
HttpResponseMessage response = new HttpResponseMessage();
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;
}
}
}
module.ts 文件
declarations: [ McDocumentsComponent,],
providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }],
bootstrap: [McDocumentsComponent]