将文件从Typescript上传到asp.net-core Web API:无法将文件作为参数传递给Web API

时间:2019-06-25 12:51:14

标签: angular typescript asp.net-core asp.net-web-api

我尝试了两种从Typescript组件调用Web api的方法:XMLHttpRequest和HttpRequest。两者具有完全相同的效果。

如果未在.send()命令中将文件作为参数发送,则可以访问Web api。发送文件会在浏览器中显示以下消息:

enter image description here

打字稿:

注意:environment.fileUploadX_Url为“ https://localhost:44387/api/UploadFile/UploadFile

connect

Web API:

   export class FileService {

  private url = environment.fileUploadX_Url;// + environment.fileUploadLoc;

  constructor(private http: HttpClient) {
  }

  upload(file: File) {

    var xhr = this.createCORSRequest('POST', this.url);
    xhr.upload.onprogress = function (event) {
      console.log('Uploaded ${event.loaded} of ${event.total}');
    };

    const fd = new FormData();
    fd.append('resultFile', file);

    xhr.send(fd);//

    //const req = new HttpRequest('POST', this.url, fd);
    //req.headers.append('Access-Control-Allow-Origin', environment.serverUrl);
    //this.http.request(req).subscribe(result => { });    

  }

  createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
      xhr.withCredentials = false;

    xhr.open(method, url, true);
    xhr.setRequestHeader("Content-Type", "multipart/form-data;");

    return xhr;
  }
}

这是我的api启动代码:

namespace Namespace.Controllers
{
    [EnableCors("ThePolicy")]
    [Route("api/[controller]")]    
    [ApiController]
    public class UploadFileController : ControllerBase
    {
        [EnableCors("ThePolicy")]
        [HttpPost, DisableRequestSizeLimit, Route("UploadFile")]
        public async Task UploadFile()
        {
            var files = Request.Form.Files;
            HttpResponseMessage res = new HttpResponseMessage();
            var filePath = "/Logs";
        }
    }
}

4 个答案:

答案 0 :(得分:0)

尝试删除Route并像这样在HttpPost中添加Route

    [HttpPost("UploadFile"), DisableRequestSizeLimit]
    public async Task UploadFile()
    {
        var files = Request.Form.Files;
        HttpResponseMessage res = new HttpResponseMessage();
        var filePath = "/Logs";
    }

似乎您的ASP.Net Core的CORS配置无法正常工作,请仔细检查。在您的Startup.cs

app.UseCors(options => options.AllowAnyOrigin());  

services.AddCors(c =>  
{  
   c.AddPolicy("AllowOrigin", options => options => options.AllowAnyOrigin());  
});  

所以在您的控制器中

[EnableCors("AllowOrigin")]
[Route("api/[controller]")]    
[ApiController]
public class UploadFileController : ControllerBase

因此无需在您的操作方法中添加EnableCors

您可以阅读此link

答案 1 :(得分:0)

您需要在Web API https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api中选中启用CORS

并将TS中的上传方法更改为

   upload(file: File) {
       const formData: FormData = new FormData();
       formData.append("file", file, file['name']);
       return this.http.post('/api/UploadFile/UploadFile', formData);
    }

答案 2 :(得分:0)

如果正确启用了CORS,则可以使用以下代码将文件发布到网络api

upload(file: File):void{      
  const formData: FormData = new FormData();     
  formData.append('image', file, file.name);
  this.http.post(this.url, formData).subscribe(result => {
     console.log(result);
  }, error => console.error(error));
}

startup.cs:

services.AddCors(options =>
        {
            options.AddPolicy("ThePolicy",
            builder =>
            {
                builder.WithOrigins("https://localhost:44323")
                                    .AllowAnyHeader()
                                    .AllowAnyMethod();
            });
        });
//Configure
app.UseCors("ThePolicy");
app.UseHttpsRedirection();
app.UseMvc();

答案 3 :(得分:0)

终于让它起作用了!我在这里尝试了所有建议,但没有一个对我有用。我恢复使用XMLHttpRequest。我要做的就是删除“ setRequestHeader”行并瞧瞧-一切正常。

这是打字稿:

List<MyObject>

这是Web API中的控制器:

export class FileService {
  _message: string;
  private url = environment.fileUploadX_Url;//this.config.FILEUPLOAD_ENDPOINT;//
  @Output('fileLoad') fileLoaded: EventEmitter<string> = new EventEmitter<string>();

  constructor(private http: HttpClient, private config: ConfigService) {
  }

  upload(file: File): void {

    var xhr = this.createCORSRequest('POST', this.url);

    const fd = new FormData();
    fd.append('file', file);

    xhr.send(fd);

  }

  createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = false;
    xhr.addEventListener('loadend', this.handleLoadEnd.bind(this));
    xhr.addEventListener('error', this.handleLoadEnd);
    xhr.open(method, url, true);


   // xhr.setRequestHeader("Content-Type", "multipart/form-data");

    return xhr;
  }

这是Web API中的startup.cs:

 [Produces("application/json")]
    [Route("api/[controller]")]    
    [ApiController]
    public class UploadFileController : ControllerBase
    {           
        [DisableRequestSizeLimit]
        [HttpPost("UploadFile")]      
        public async Task<ActionResult> UploadFile()
        {
            try
            {                                
                var file = Request.Form.Files[0];
                string fileName = file.FileName;
                var filePath = Path.Combine("/Logs", fileName);

                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
            }
            catch (Exception ex) {
                return BadRequest("Unable to upload the file." );
            }

            return  Ok();
        }


    }