如何将文件从Postman上传到Controller

ldfqzlk8  于 11个月前  发布在  Postman
关注(0)|答案(2)|浏览(150)

我已经阅读了很多帖子和文章,仍然不知道为什么我的请求失败。有一个asp net core 3.1应用程序。简单的控制器代码:

[Route("api/v1/user")]
public class BlobController : Controller
{
    [HttpPost("uploadphoto")]
    public async Task<UploadPhotoResponse> UploadPhoto([FromForm] IFormFile file)
    {
        return null;
    }
}

字符串


的数据
Postman 要求:



标题:



每次我得到400错误的请求结果,无法进入AdmadPhoto方法。

mzsu5hc0

mzsu5hc01#

IFormFile更改为UploadPhotoRequest--> multipart file

using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace UploadPhoto.Controllers
{

    public class UploadPhotoRequest
    {
        public IFormFile File { get; set; }
        public string Name { get; set; }

        public string FileName { get; set; }
    }

    [ApiController]
    [Route("api/v1/user")]
    public class WeatherForecastController : ControllerBase
    {

        [HttpPost("uploadphoto")]
        public string UploadPhoto([FromForm] UploadPhotoRequest file)
        {
            Console.WriteLine(file.Name);
            return file.Name;

        }
    }
}

字符串

Postman Collection验证

{"auth":null,"event":null,"info":{"_postman_id":null,"description":null,"name":"test.http","schema":"https://schema.getpostman.com/json/collection/v2.1.0/collection.json","version":null},"item":[{"description":null,"event":null,"id":null,"name":"1","protocolProfileBehavior":null,"request":{"auth":null,"body":{"disabled":null,"file":null,"formdata":[{"contentType":"application/json","description":null,"disabled":null,"key":"image","type":"file","value":"settings.json","src":null},{"contentType":null,"description":null,"disabled":null,"key":"name","type":"text","value":"ram","src":null}],"graphql":null,"mode":"formdata","options":null,"raw":null,"urlencoded":null},"certificate":null,"description":"1","header":null,"method":"POST","proxy":null,"url":"https://localhost:5001/api/v1/user/uploadphoto"},"response":null,"variable":null,"auth":null,"item":null}],"protocolProfileBehavior":null,"variable":null}


有两种方法可以上传文件。
1.通过单个文件扩展
1.通过多部分扩展
如果有多个文件/字段要上传,则使用此选项

Postman中上传单个文件

1.切换到正文选项卡
1.选择二进制
1.选择文件x1c 0d1x

Postman上传分块文件

1.切换到正文选项卡
1.选择表单数据
1.添加关键点
如果它是一个文件,悬停到键的右边部分.你将看到选项来改变它到文件.


备选方案

Dothttp是一个类似的工具,可以很好地控制这些。

单个文件

POST https://req.dothttp.dev
// select as a binary
fileinput('C:\Users\john\documents\photo.jpg') // path to file

分块上传

POST https://req.dothttp.dev
// selects as multipart 
multipart(
    'name'< 'john',
    'photo'< 'C:\Users\john\documents\photo.jpg',
// and many more
)

6gpjuf90

6gpjuf902#

虽然听起来很奇怪,但请确保在控制器中使用“file”作为参数名称,例如

public async Task<IActionResult> CheckContent(IFormFile file)

字符串
我可以从Postman发布到MVC控制器的唯一方法
记得关掉你的防伪系统

相关问题