reactjs - 使用 ASP.Net Core 2.0 Web API 和 React.js 上传文件

标签 reactjs file-upload asp.net-core-2.0

我对react.js 和 ASP.Net core 2.0 都很陌生。现在正在编写一个使用ASP.Net core 2.0作为后端API和react.js作为应用程序接口(interface)(前端)的项目。我想知道如何上传文件。我已尝试如下,但在后端,参数值(IFromFile 文件)始终为空。并且该文件似乎未正确发布。这是我的代码:

.Net核心(API)

[HttpPost]
        [Route("upload")]
        public async Task Upload(IFormFile file)
        {
            if (file == null) throw new Exception("File is null");
            if (file.Length == 0) throw new Exception("File is empty");

            using (Stream stream = file.OpenReadStream())
            {
                using (var binaryReader = new BinaryReader(stream))
                {
                    var fileContent =  binaryReader.ReadBytes((int)file.Length);
                   // await _uploadService.AddFile(fileContent, file.FileName, file.ContentType);
                }
            }
        }

React.js

handleClick(event){
        event.preventDefault();
        // console.log("handleClick",event);
        var self = this;
        var apiBaseUrl =  axios.defaults.baseURL + "user/upload";
        if(this.state.filesToBeSent.length>0){
            var filesArray = this.state.filesToBeSent;
            const reader = new FileReader();
            for(var i in filesArray){
                //console.log("files",filesArray[i][0]);
                var file = filesArray[i][0];
                axios.post(apiBaseUrl, {data: file});
            }
            alert("File upload completed");
        }
        else{
            alert("Please select files first");
        }
    }

请告诉我如何解决这个问题。

最佳答案

我完成了以下工作:

在.Net core 2.0 Web api

使用 Microsoft.AspNetCore.Http;

我创建了一个模型类

namespace Marter_MRM.Models
{
    public class FileUploadViewModel
    {
        public IFormFile File { get; set; }
        public string source { get; set; }
        public long Size { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
        public string Extension { get; set; }
    }
}

然后我创建了一个 Controller 类并编写了如下函数。

[HttpPost]
[Route("upload")]
public async Task<IActionResult> Upload(FileUploadViewModel model) {
      var file = model.File;

      if (file.Length > 0) {
           string path = Path.Combine(_env.WebRootPath, "uploadFiles");
           using (var fs = new FileStream(Path.Combine(path, file.FileName), FileMode.Create))
           {
                await file.CopyToAsync(fs);
           }

           model.source = $"/uploadFiles{file.FileName}";
           model.Extension = Path.GetExtension(file.FileName).Substring(1);
      }
    return BadRequest();
}

并在react中编写api调用函数如下:

handleUploadClick(event){
    event.preventDefault();
    var self = this;
    var apiBaseUrl =  axios.defaults.baseURL + "user/upload";
    if(this.state.filesToBeSent.length>0){
        var filesArray = this.state.filesToBeSent;
        let f = new FormData();
        for(var i in filesArray){
        //console.log("files",filesArray[i][0]);
             f = new FormData();
             f.append("File",filesArray[i][0] )
             axios.post(apiBaseUrl, f, {
                    headers: {'Content-Type': 'multipart/form-data'}
             });
        }
        alert("File upload completed");
    }
    else{
        alert("Please select files first");
    }
}

它工作完美。谢谢!

关于reactjs - 使用 ASP.Net Core 2.0 Web API 和 React.js 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46391735/

相关文章:

c# - Dot Net Core 2.0 多重cookie

javascript - 根据另一个 reducer 的状态更新一个 reducer 的状态

javascript - 如何使用 minibuffer 设置 React js 文件的 web-mode-content-type

javascript - 如何在 React.js 中编辑多个元素的样式

PHP 文件上传不适用于 mp4

azure - 在服务结构中使用的环境变量 ASPNETCORE_ENVIRONMENT 是什么

reactjs - 如何从mapDispatchToProps内部访问状态

php - PhoneGap Build API : CURL Command Line to PHP

javascript - 通过调用 Web 服务从 JavaScript 上传文件

asp.net-mvc - 过滤器后的 asp.net 核心验证