【问题标题】:How to upload file to asp .net?如何将文件上传到asp .net?
【发布时间】:2020-03-17 18:46:44
【问题描述】:

我正在寻找有关如何使用表单将文件发送到 asp 应用程序的解决方案。我正在使用 asp .net 框架 MVC Razor 编写。

我的表格:

<div class="container">
    <div class="col-md-2">
        @using (Html.BeginForm("Data", "Admin", FormMethod.Post, new { encrypte = "multipart/form-data"}))
        {
            <div class="form login-form">
                <label for="username" class="text-info">Wczytaj plik:</label>
                <input type="file" name="file" id="file" />
            </div>
            <div id="register-link" class="text-right">
                <input type="submit" class="btn btn-success" value="Importuj" />
            </div>
            @ViewBag.Message
        }
    </div>
</div>

我的控制器:


        [HttpPost]
        public ViewResult Data(HttpPostedFile file = null)
        {
            if(file != null && file.ContentLength > 0)
            {
                string path = Path.Combine(Server.MapPath("~/Upload/Data"), Path.GetFileName(file.FileName));
                file.SaveAs(path);
                ViewBag.Message = "Succes";
            }

            return View("AdminDataView", students);
        }

很遗憾,上面的代码不起作用,是我做错了什么吗,还有其他选项可以将文件上传到asp吗?

【问题讨论】:

  • “上面的代码不起作用”有错误吗?您收到成功消息了吗?你试过调试吗?
  • 我没有错误。所以我调试了代码:我加载文件并发送表单,在控制器中传递的对象为空并返回到原始视图。

标签: c# asp.net-mvc razor


【解决方案1】:

我认为有一个错字,我建议你使用ActionResult 而不是ViewResult

Defference between ActionResult & ViewResult

错字是:new { enctype="multipart/form-data"}) 不是 new { encrypte = "multipart/form-data"})

示例代码:

查看

@using(Html.BeginForm("UploadFile","Upload", FormMethod.Post, new { 
enctype="multipart/form-data"}))  
{  
    <div>  
        @Html.TextBox("file", "", new {  type= "file"}) <br />  
        <input type="submit" value="Upload" />  
        @ViewBag.Message  
    </div>     
}

控制器

    [HttpPost]  
    publicActionResultUploadFile(HttpPostedFileBase file)  
    {  
        try  
        {  
            if (file.ContentLength > 0)  
            {  
                string _FileName = Path.GetFileName(file.FileName);  
                string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);  
                file.SaveAs(_path);  
            }  
            ViewBag.Message = "File Uploaded Successfully!!";  
            return View();  
        }  
        catch  
        {  
            ViewBag.Message = "File upload failed!!";  
            return View();  
        }  
    } 

【讨论】:

    【解决方案2】:

    请参考下面的链接,这可以让您更好地理解。

    https://stackoverflow.com/a/60519052/7761461

    希望这对你有帮助。

    【讨论】:

      猜你喜欢
      • 2013-11-11
      • 2013-09-15
      • 2015-10-20
      • 1970-01-01
      • 2016-07-25
      • 2016-06-06
      • 2014-07-21
      • 2021-12-25
      • 1970-01-01
      相关资源
      最近更新 更多