【问题标题】:asp.net core web API file upload and "form-data" multiple parameter passing to methodasp.net core web API 文件上传和“form-data”多个参数传递给方法
【发布时间】:2019-01-24 08:06:48
【问题描述】:

我创建了一个以文件为参数的端点:

    [HttpPost("[action]")]
    [Consumes("multipart/form-data")]
    public ActionResult UploadImage(IFormFile  Files, string param)
    {

        long size = Files.Length;            
        var tempPath = Path.GetTempFileName();
        string file_Extension = Path.GetExtension(Files.FileName);                   
        var isValidFile = FileValidation.FileUploadValidation(Files);
        if (isValidFile.data)
        {
            string filename = Guid.NewGuid() + "" + file_Extension;
            return null;

        }
        else
        {
            return null;
        }
    }

我无法毫无问题地检索文件。 如何在同一个方法中添加更多的文本参数?

【问题讨论】:

标签: asp.net-mvc azure asp.net-core .net-core


【解决方案1】:
[HttpPost("[action]")]
[Consumes("multipart/form-data")]
public IActionResult UploadImage([FromForm] FileInputModel Files)
{

    return Ok();
}

public class FileInputModel 
{
    public IFormFile File { get; set; }
    public string Param { get; set; }
}

我添加[FromForm]代码后需要在参数模型前添加[FromForm]才能完美运行。

【讨论】:

  • 其实我需要发送 FileInputModel 的列表。需要明确的是,每个文件都有自己独特的参数。当我尝试发送“List model”时,动作是堆栈,我无法得到任何响应。你有什么想法吗?
【解决方案2】:

它 100% 有效。经测试。请执行以下步骤:

你应该为模型创建一个自定义类

public class FileInputModel
{
    public string Name { get; set; }
    public IFormFile FileToUpload { get; set; }
}

和类似的形式

<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="UploadFileViaModel" >
    <input name="Name" class="form-control" />
    <input name="FileToUpload" type="file" class="form-control" />
    <input type="submit" value="Create" class="btn btn-default" />
</form>

和控制器方法类似

[HttpPost]
public async Task<IActionResult> UploadFileViaModel([FromForm] FileInputModel model)
{
    if (model == null || model.FileToUpload == null || model.FileToUpload.Length == 0)
        return Content("file not selected");

    var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", model.FileToUpload.FileName);

    using (var stream = new FileStream(path, FileMode.Create))
    {
        await model.FileToUpload.CopyToAsync(stream);
    }

    return RedirectToAction("Files");
}

【讨论】:

    【解决方案3】:

    我用以下代码进行了测试,它可以工作:

    public class TestController : Controller
    {
        [HttpPost("[controller]/[action]")]
        public IActionResult Upload(Model model)
        {
            return Ok();
        }
    
        public class Model
        {
            public IFormFile File { get; set; }
            public string Param { get; set; }
        }
    }
    

    请注意,您需要使用模型。

    这是下面具有相同属性的邮递员屏幕截图。

    更新多个文件:

    将模型更改为:

    public class Model
    {
        public List<IFormFile> Files { get; set; }
        public string Param { get; set; }
    }
    

    邮递员截图:

    更新 2

    内容类型标头为multipart/form-data

    这是它的工作截图:

    【讨论】:

    • 仍然无法正常工作,标题内容类型是什么?
    • @DinukaWanasinghe 已更新,请确保您删除了 [Consumes] 属性。
    • 这只对我有用 [Consumes][FromForm] 提示。不知道为什么。
    • 这将在没有内容类型的情况下工作,请尝试从标题中删除内容类型
    【解决方案4】:

    C# .NET 核心

    [HttpPost("someId/{someId}/someString/{someString}")]
    [ProducesResponseType(typeof(List<SomeResponse>), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status401Unauthorized)]
    [ProducesResponseType(StatusCodes.Status403Forbidden)]
    [ProducesResponseType(typeof(Dictionary<string, string[]>), StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> Post(int someId, string someString, [FromForm] IList<IFormFile> files)
    {
    ...
    }
    

    打字稿:

    create(someId: number, someString: string, files: File[]) {
        var url = `${this.getBaseUrl()}/someId/${someId}/someString/${someString}`;
    
        const form = new FormData();
        for (let file of files) {
            form.append("files", file);
        }
    
        return this.http.post<SomeResponse>(url, form, {
            reportProgress: true,
        });
    }
    

    【讨论】:

    • 设置标头 'Content-Type': 'application/json' 如果实现是有角度的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-05
    • 2018-07-05
    • 2018-01-27
    • 2010-11-27
    • 1970-01-01
    • 2021-08-09
    • 2020-08-25
    相关资源
    最近更新 更多