.NET Core-如何将文件作为参数从View传递到Controller?

时间:2018-09-06 14:44:35

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

我必须创建API以从JSON文件读取数据并将其保存到数据库中。所以我做到了,当我使用邮递员发送文件时,它工作正常。但是我还需要能够使用表单执行相同的操作,而我无法找到解决方案。

ImportController.cs

[Produces("application/json")]
[Route("api/Import")]
public class ImportController : ControllerBase
{

    private readonly DbContext dbContext;

    public ImportController(DbContext dbContext)
    {
        this.dbContext = dbContext;
    }

    [HttpPost]
    [Route("ImportData")]
    public IActionResult ImportData(IFormFile file)
    {

        var content = string.Empty;

        using (var reader = new StreamReader(file.OpenReadStream()))
        {
            content = reader.ReadToEnd();
        }

        List<UserImportModel> userObjects = null;
        try
        {
            userObjects = JsonConvert.DeserializeObject<List<UserImportModel>>(content);
        }
        catch
        {
            return BadRequest();
        }

        foreach (var user in userObjects)
        {

            UserModel us = new UserModel
            {
                Username = user.Username,
                Password = user.Password,
                Created = DateTime.UtcNow
            };

            dbContext.User.Add(us);
            dbContext.SaveChanges();
        }

        return Ok();
    }

我认为表格

    <form method="post" enctype="multipart/form-data" action="../api/Import/ImportData">
         <input type="file" name="file" id="file">
         <input type="submit" value="Upload file" name="submit">
    </form>

当我在浏览器中输入Developer Tools并单击Submit时,以下数据将显示为POST参数:

-----------------------------209091002211274
Content-Disposition: form-data; name="file"; filename="test.json"
Content-Type: application/json

[{"Username":"user1","Password":"123456"},{"Username":"user2","Password":"654321"}]
-----------------------------209091002211274
Content-Disposition: form-data; name="submit"

Upload file
-----------------------------209091002211274--

这使我相信文件及其数据已发送,对吗?

1 个答案:

答案 0 :(得分:0)

我认为这是因为它是对象的数组[],而不是JSON集合{}