ASPNetCore - 通过 REST 上传文件 [英] ASPNetCore - Uploading a file through REST

查看:26
本文介绍了ASPNetCore - 通过 REST 上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Insomnia 测试 API,但 Postman 也是如此.

I am using Insomnia for testing an API, but the same happens with Postman.

我想使用以下控制器测试文件上传:

I want to test a file upload, with the following controller:

public async Task<IActionResult> Post([FromForm]IFormFile File)

如果我将请求设置为多部分请求:

If I set the request as a multipart request:

它有效.

但是,如果我将其设置为二进制文件:

However, if I set it as a binary file:

我不知道如何获取数据.怎么办?

I don't know how to get the data. How can it be done?

另外,在控制器方法的签名中,如果我将 [FromForm] 更改为 [FromBody],我将无法获取数据.

Also, in the controller method's signature, if I change [FromForm] to [FromBody], I'm not getting data.

有人可以帮我澄清一下吗?

Can someone clarify this for me?

推荐答案

正如您已经注意到的,在 Postman/Insomnia 中使用 binary file 选项并不是标准方式.通过 RESTful API 上传文件有三种不同的方式,您必须选择一种.

As you've noticed already, using binary file option in Postman/Insomnia doesn't work the standard way. There are three different ways to upload file via RESTful API, and you have to choose one.

我已经包含了将上传的文件内容读取为字符串并将其输出的代码片段 - 尝试发送一个文本文件,您应该在 200 响应中获得该文件的内容.

I've included code snippets that read the uploaded file contents to a string and output it -- try sending a text file, and you should get the contents of the file in the 200 response.

表单数据上传

这是最流行/知名的上传方法,将您发送的数据格式化为一组键/值对.一般需要在请求中指定Content-Typemultipart/form-data,然后在MVC中使用[FromForm]属性绑定变量的值.另外,您可以使用内置的 IFormFile 类来访问上传的文件.

This is the most popular/well-known upload method formatting the data you send as a set of key/value pairs. You normally need to specify Content-Type to multipart/form-data in the request, and then use [FromForm] attribute in MVC to bind values to variables. Also, you can use the built-in IFormFile class to access the file uploaded.

[HttpPost]
public async Task<IActionResult> PostFormData([FromForm] IFormFile file)
{
    using (var sr = new StreamReader(file.OpenReadStream()))
    {
        var content = await sr.ReadToEndAsync();
        return Ok(content);
    }
}

正文上传

您可以以 MVC 可以理解的格式发送正文,例如JSON,并将文件嵌入其中.通常,文件内容将使用 Base64 或其他编码进行编码,以防止出现字符编码/解码问题,尤其是在发送图像或二进制数据时.例如

You can send body in the format that MVC understands, e.g. JSON, and embed the file inside it. Normally, the file contents would be encoded using Base64 or other encoding to prevent character encoding/decoding issues, especially if you are sending images or binary data. E.g.

{
    "file": "MTIz"
}

然后在你的控制器中指定[FromBody],并使用class进行模型反序列化.

And then specify [FromBody] inside your controller, and use class for model deserialization.

[HttpPost]
public IActionResult PostBody([FromBody] UploadModel uploadModel)
{
    var bytes = Convert.FromBase64String(uploadModel.File);
    var decodedString = Encoding.UTF8.GetString(bytes);
    return Ok(decodedString);
}
// ...
public class UploadModel
{
    public string File { get; set; }
}

当使用大型非文本文件时,JSON 请求会变得笨重且难以阅读.

When using large and non-text files, the JSON request becomes clunky and hard to read though.

二进制文件

这里的关键是您的文件是整个请求.该请求不包含任何其他信息来帮助 MVC 将值绑定到代码中的变量.因此,要访问该文件,需要读取Request中的Body.

The key point here is that your file is the whole request. The request doesn't contain any additional info to help MVC to bind values to variables in your code. Therefore, to access the file, you need to read Body in the Request.

[HttpPost]
public async Task<IActionResult> PostBinary()
{
    using (var sr = new StreamReader(Request.Body))
    {
        var body = await sr.ReadToEndAsync();
        return Ok(body);
    }
}

注意:示例将 Body 读取为 string.您可能希望在应用程序中使用 Streambyte[] 以避免文件数据编码问题.

Note: the example reads Body as string. You may want to use Stream or byte[] in your application to avoid file data encoding issues.

这篇关于ASPNetCore - 通过 REST 上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆