【问题标题】:Struggle with file upload .net core MVC与文件上传.net核心MVC斗争
【发布时间】:2021-12-24 12:43:50
【问题描述】:

经过几天的谷歌搜索和尝试,我无法将 xsd 文件上传到网络服务器。

这里是创建表单:

<form asp-action="Create" enctype="multipart/form-data" method="post">
<input asp-for="catname" class="form-control" />
<input type="file" asp-for="xsddata" class="form-control" />
<input type="submit" value="Create" class="btn btn-primary" />
</form>

模型如下所示:

public class cat{
[Key]
public int catid { get; set; }
public string catname { get; set; }
public string xsddata { get; set; }}

我只想将路径和文件名保存在数据库中。

在控制器类中我添加了保存方法:

[HttpPost]
    public async Task<IActionResult> Upload([FromForm]IFormFile file)
    {
        var path = Startup.myAppPath();
        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);
        FileInfo fileInfo = new FileInfo(file.FileName);
        var fullPath = Path.Combine(path, fileInfo.Name);
        if (!System.IO.File.Exists(fullPath))
        {
            using (FileStream fileStream = new FileStream(fullPath, FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }
            return new JsonResult(new { FileName = fileInfo.Name });
        }
        return BadRequest();
    }

但是现在,即使在我选择了一个文件并且在我点击“提交”按钮之前,IDE 也会崩溃。

这让我疯狂了好几天,我找不到可以依赖的例子。 如果你们能帮帮我就好了。

【问题讨论】:

    标签: c# file upload asp.net-core-mvc


    【解决方案1】:

    我的建议是:为什么你的 IDE 在你选择一个文件之后提交它之前会崩溃?您是否尝试选择一些不同大小的文件?

    在你的控制器中,代码与模型无关,你可以尝试更改一些代码。

    首先,改变model中‘xsddata’的类型:

    型号:

    public class Cat
    {
    [Key]
    public int catid { get; set; }
    public string catname { get; set; }
    public IFormFile xsddata { get; set; }
    }
    

    查看:

    <div>
    <h4>File in Model Upload</h4>
    <form asp-controller="Home" asp-action="FileUpLoad" enctype="multipart/form-data" method="post">
    <input type="text" name="cat.catid" />
    <input type="text" name="cat.catname" />
    <input type="file" name=cat.xsddata />
    <button type="submit">Submit</button>
    </form>
    </div>
    

    你可以得到这个表格,填写catid和catname,选择一个文件并提交:

    然后,您可以在控制器中接收值:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-19
      • 2011-01-16
      • 2020-09-18
      • 2018-05-23
      • 2013-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多