javascript 是否在ASP.NET Core后端接收fetch()二进制流?

ghhkc1vu  于 2023-06-28  发布在  Java
关注(0)|答案(1)|浏览(104)

在我的前端,我上传了一个文件到我的后端,其中包含以下JavaScript代码:

const file = document.getElementById('file');

const response = await fetch("https://localhost:5333/upload", {
    method: 'POST',
    body: file
});

console.log(`upload response status code: ${response.status} ${response.statusText}`);
const json = await response.json();

console.log(`response json: ${JSON.stringify(json) }`);

(我不想使用FormData,因为我只上传一个文件)
我的控制器看起来像这样:

[ApiController]
[Route("[controller]")]
public class UploadController : ControllerBase
{
    [HttpPost]
    public UploadResponse Upload() // <----- which parameter type do I need here?
    {
        return new UploadResponse
        {
            SomeProperty = "some value"
        };
    }
}

我的后端Upload()方法需要哪个参数类型来从前端接收文件作为流?

toe95027

toe950271#

通常你会使用IFormFile类:

[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
    if (file == null || file.Length == 0)
    {
        return BadRequest("No file provided");
    }

    //to do

    return Ok(new UploadResponse
    {
        SomeProperty = "some value"
    });
}

相关问题