使用.NET Core 2.0 Web api上传HTML5文件

问题描述 投票:1回答:2

这个问题可能是重复的,在这种情况下,我希望得到一个阅读,但请检查重复的问题是否适合我的。我试过寻找答案,但没有找到任何符合我问题的答案。

我有一个使用React构建的网站,该网站由.NET Core 2.0项目提供,其中包含从内置于项目中的常规Controller web api生成的常规Web API。 Web API的设置如下:

[Produces("application/json")]
[Route("api/File")]
public class FileController : Controller
{      
    // POST: api/File
    [HttpPost]
    public ActionResult Post()
    {
        Console.WriteLine(Request);
        return null;
    }

我想从常规的input type="file"字段上传图像/ PDF文件和其他文件类型。

代码可以在下面看到:

export class Home extends Component {
  render() {
    return <input type = "file"
    onChange = {
      this.handleFileUpload
    }
    />
  }

  handleFileUpload = (event) => {
    var file = event.target.files[0];
    var xhr = new XMLHttpRequest();
    var fd = new FormData();
    xhr.open("POST", 'api/File', true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4 && xhr.status == 200) {
        // Every thing ok, file uploaded
        console.log(xhr.responseText); // handle response.
      }
    };
    fd.append("upload_file", file);
    xhr.send(fd);
  }
}

需要在Post-file-controller部分中实现什么才能正确处理文件?如果我想要将文件上传为,例如uint8数组(要存储)。

我被困住了,所有的帮助都很受欢迎。

javascript html5 reactjs .net-core-2.0
2个回答
2
投票

我有点迟到了,但如果有其他人在解决这个问题:后端参数file在我的情况下为空的原因是因为前端的输入名称必须与后端的方法参数名称相同。

在您的示例中,您选择了输入名称upload_file

fd.append("upload_file", file);

所以后端的参数必须具有相同的名称:

[HttpPost]
public void PostFile(IFormFile upload_file)
{
    _fileService.Add(upload_file);
}

1
投票

我会假设你的意思byte[]uint8 array。您可以尝试使用新的IFormFile界面。

[Route("api/File")]
public class FileController : Controller
{      
    // POST: api/file
    [HttpPost]
    public ActionResult Post(IFormFile file)
    {
     var uploadPath = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
     if (file.Length > 0) {
            var filePath = Path.Combine(uploads, file.FileName);
            using (var fileStream = new FileStream(filePath, FileMode.Create)) {
            //You can do anything with the stream e.g convert it to byte[]
            byte[] fileBytes = new byte[fileStream.Length];
            //Read the stream and write bytes to fileBytes 
            fileStream.Read(fileBytes, 0, fileBytes.Length);
            //fileBytes will contain the file byte[] at this point
            //Persist the file to disk
            await file.CopyToAsync(fileStream);
            }
        }
       //....
    }

编辑:确保参数名称IFormFile file*与您从客户端发送的名称相匹配,在您的情况下,它应该是IFormFile upload_file

© www.soinside.com 2019 - 2024. All rights reserved.