【发布时间】:2017-11-20 17:54:50
【问题描述】:
我正在使用在本地//4200 上运行的 angular4.2 cli 和在本地//62567 上运行的 asp.netCore。
在我的 asp.net core 启动课程中,我允许:
//add cors service
services.AddCors(options => options.AddPolicy("Cors",
builder => {
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
);
当我发送我的帖子请求时,我得到了这个:
:65223/api/Net:1 POST http://localhost:65223/api/Net 500 (Internal Server Error
XMLHttpRequest cannot load http://localhost:65223/api/Net. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 500.
然后我在回复中添加了以下标题:
'Access-Control-Allow-Origin:*'
我在我的控制器上启用了 cors,但我是 javascript 新手,并且使用 http 通过 api 传输文件。我很困惑什么是最好的方法来做到这一点。在使用二进制类型时,最好发送表单还是二进制字节数组。两种不同的语言如何在任何给定时间知道文件的确切内容。我将在下面发布我的代码,感谢您抽出时间阅读本文。
.Net
[EnableCors("Cors")]
[HttpPost]
public async Task<IActionResult> Post(ICollection<IFormFile> files)
{
var uploader= Path.Combine(_environment.WebRootPath, "Uploads");
foreach (var file in files)
{
if (file.Length > 0)
{
using (var fileStream = new FileStream(Path.Combine(uploader, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
}
return Created(uploader, files);
}
Angular4.2+
组件:
@Component({
selector: 'new-upload',
template: `
<mat-card class="card">
<mat-card-content>
<mat-form-field>
<input matInput [(ngModel)]="message.owner" placeholder="Name">
</mat-form-field>
<input type="file" name="file" (change)="getFiles($event)">
<mat-card-actions>
<button (click)="post()" mat-raised-button color="primary">POST</button>
</mat-card-actions>
</mat-card-content>
</mat-card>
`
})
export class UploadComponent {
constructor(private uploadService: UploadService) {}
files : FileList;
getFiles(event){
this.files = event.target.files;
this.message.img = event.target.files;//injected new file from server
}
logForm(event) {
console.log(this.files);
}
message = {
owner: '',
img:FileList //made new file list t
}
post() {
this.uploadService.postMessages(this.message);
console.log(this.message)
console.log(this.message.text)
}
}
【问题讨论】:
标签: javascript asp.net angular http asp.net-core-2.0