将图像从 Angular 8 上传到 ASP.Netcore Web API 时遇到问题

我花了一整天的时间试图让它发挥作用,我查看了以下内容:

还有很多我数不过来的。

我想要的只是发送一份表格和一张图像。得到的错误是:

  • 缺少内容类型边界

  • 内容类型不正确

  • 函数求值需要所有线程运行

有角的

register(user: UserViewModel, logo: File) {

    // We use formData because we can't send file as an object

    const formData = new FormData();


    formData.append("user", JSON.stringify(user));


    formData.append("logo", logo);


    console.log(formData);


    return this.http.post<UserRegisterViewModel>(`${UserAPI.API_User}/${"register"}`, formData).pipe(map(user => {


      return user;


    }));

  }

我的 C# 代码看起来像这样


[HttpPost, DisableRequestSizeLimit]

        [AllowAnonymous]

        [Route("register")]

        //[Consumes("application/json", "multipart/form-data")]

        public async Task<IActionResult> RegisterAsync()

        {


            IFormFile logo = null;


            try

            {


                // Get the logo

                logo = Request.Form.Files[0];

                // Get the user json string

                var userJson = Request.Form["user"];


繁星淼淼
浏览 66回答 2
2回答

HUWWW

如果您想从 获取文件Request.Form。您可以按照以下代码示例操作:客户端 :const formData = new FormData();formData.append('file', fileToUpload, fileToUpload.name);this.http.post('https://localhost:5001/api/upload', formData, {reportProgress: true, observe: 'events'}).subscribe(event => {&nbsp; &nbsp; if (event.type === HttpEventType.UploadProgress)&nbsp; &nbsp; this.progress = Math.round(100 * event.loaded / event.total);&nbsp; &nbsp; else if (event.type === HttpEventType.Response) {&nbsp; &nbsp; this.message = 'Upload success.';&nbsp; &nbsp; this.onUploadFinished.emit(event.body);&nbsp; &nbsp; }});服务器端 :[HttpPost, DisableRequestSizeLimit]public IActionResult Upload(){&nbsp; &nbsp; try&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var file = Request.Form.Files[0];&nbsp; &nbsp; &nbsp; &nbsp; var folderName = Path.Combine("StaticFiles", "Images");&nbsp; &nbsp; &nbsp; &nbsp; var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);&nbsp; &nbsp; &nbsp; &nbsp;.....&nbsp; &nbsp; }&nbsp; &nbsp; catch (Exception ex)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;....&nbsp; &nbsp; }}或者您可以使用 FromForm 获取文件:客户端 :let fileToUpload = <File>files[0];const formData = new FormData();formData.append('file', fileToUpload, fileToUpload.name);this.http.post('YourURL', formData, {headers: {&nbsp; 'Accept': 'application/json',&nbsp; &nbsp; &nbsp;&nbsp; 'Content-Disposition' : 'multipart/form-data'},reportProgress: true, observe: 'events'})&nbsp; .subscribe(event => {&nbsp; &nbsp; ....&nbsp; });那么服务器端将是:[HttpPost, DisableRequestSizeLimit]public IActionResult Upload([FromForm(Name = "file")] IFormFile file){}

守候你守候我

这解决了它,我有一个断点logo = Request.Form.Files[0];由于某种原因,VS2017 和 2019 中存在一个错误。
打开App,查看更多内容
随时随地看视频慕课网APP