【问题标题】:What is the right way to send file types from angular4 to asp.netcore?将文件类型从 Angular 发送到 asp.net 核心的正确方法是什么?
【发布时间】: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


    【解决方案1】:

    每当您处理文件时,您必须将表单值编码为FormData,然后再将它们发布到服务器。以下面的代码为例,

    let formData = new FormData();
    formData.append("files", this.files);
    
    this.uploadService.post(formData).subscribe();
    

    在 MVC/Razor 页面中,表单属性 enctype='multipart/form-data' 自动将您的表单值编码为 FormData。但在 Angular/Ajax 中,您必须自己完成编码部分,它会通过 http 发送整个文件(您不必将其转换为二进制类型数组)。

    只有当您通过 http 发布该文件时,服务器才知道该文件。发布后,您可以检查IFormFile 的不同属性(它基本上代表整个文件)以了解文件究竟包含什么。

    在客户端,如果您确实想知道文件究竟包含什么,您可以使用FileReader API 来读取文件内容。

    【讨论】:

    • 它说它已创建但我没有将物理文件放入上传文件夹。有没有办法从 IFormFile 中提取一个图像文件。老实说,我只是对此感到沮丧。它说它可以工作,但我在上传文件夹中没有看到文件
    • 显然 chrome 会阻止来自同一域 origin 的 Xmlhttprequests。我在前端都在本地主机上工作 - 在不同端口上运行的后端和 chrome 在看到文件上传事件时将选项放在标题中。
    猜你喜欢
    • 1970-01-01
    • 2023-02-21
    • 2019-10-10
    • 2012-08-27
    • 1970-01-01
    • 2021-05-25
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多