为什么MVC HttpPostedFileBase始终为空? [英] Why is MVC HttpPostedFileBase always null?

查看:197
本文介绍了为什么MVC HttpPostedFileBase始终为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的观点

测试上传档案



 < ; form action =@ Url.Action(Index,Home)method =postenctype =multipart / form-data> 
@ Html.AntiForgeryToken()
< label for =file>文件名:< / label>
< input type =filename =filesid =files/>

< input type =submitname =submitvalue =Upload/>
< / form>

这是我的控制器

 public Valid ActionResult Index(IEnumerable< HttpPostedFileBase> files)
{
if(files!= null)
{
foreach(var file in files)
{
try
{
if(file!= null&& file.ContentLength> 0)
{
var fileName = file.FileName;
var path = Path.Combine(Server.MapPath(@\Upload),fileName);
file.SaveAs(path);

ViewBag.Message =文件上传成功;

$ b $ catch(Exception ex)
{
ViewBag.Message =ERROR:+ ex.Message.ToString();
}
}
}
return View();
}

问题是HttpPostedFileBase文件始终为空。我无法找到问题。



< img src =https://i.stack.imgur.com/VR0fx.pngalt =在这里输入图片描述>

解决


$ b

> postenctype =multipart / form-data>

< label for =file>档案名称:< / label>
< input type =filename =filesid =files/>

< input type =submitname =submitvalue =Upload/>
< / form>





脚本

 < script type =text / javascript> 
var form = document.getElementById('formTest')。onsubmit = function(e){
e.preventDefault();
var formdata = new FormData(); // FormData对象
var fileInput = document.getElementById('files');
if(fileInput!=&& fileInput.files.length> 0){
//遍历fileInput中选定的每个文件
for(i = 0; i< ; fileInput.files.length; i ++){
//将每个文件附加到FormData对象
formdata.append(fileInput.files [i] .name,fileInput.files [i]);

//创建一个XMLHttpRequest并发送
var xhr = new XMLHttpRequest();

var url ='@ Url.Action(Index,Home)';
xhr.open('POST',url);
xhr.send(formdata);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4&&xhr.status == 200){
var result = xhr.responseText;

}
}
return false;
}
}
< / script>



C#
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ if $
{
var file = Request.Files [0];
if(file!= null&& file.ContentLength> 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath(〜/ Images /),fileName);
file.SaveAs(path);
}
return View();

}
}


This is my View

Test Upload File

<form action="@Url.Action("Index", "Home")" method="post" enctype="multipart/form-data">
    @Html.AntiForgeryToken()
    <label for="file">Filename:</label>
    <input type="file" name="files" id="files" />

    <input type="submit" name="submit" value="Upload" />
</form>

This is my Controller

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
          { 
              if (files != null)
                {
                 foreach (var file in files)
                   {
                    try
                     {
                      if (file != null && file.ContentLength > 0)
                        {
                          var fileName = file.FileName;
                          var path = Path.Combine(Server.MapPath(@"\Upload"), fileName);
                          file.SaveAs(path);

                          ViewBag.Message = "File uploaded successfully";
                         }
                       }
                      catch (Exception ex)
                      {
                        ViewBag.Message = "ERROR:" + ex.Message.ToString();
                       }
                   }
                 }
               return View();
             }

The problem is the HttpPostedFileBase files is always null. I cant find the problem.

解决方案

Here is an example how to use form onsubmit method

Your HTML part

<form id="formTest" method="post" enctype="multipart/form-data">

        <label for="file">Filename:</label>
        <input type="file" name="files" id="files" />

        <input type="submit" name="submit" value="Upload" />
    </form>


script

<script type="text/javascript">
var form = document.getElementById('formTest').onsubmit = function (e) {
        e.preventDefault();
    var formdata = new FormData(); //FormData object
    var fileInput = document.getElementById('files');
    if (fileInput != "" && fileInput.files.length > 0) {
        //Iterating through each files selected in fileInput
        for (i = 0; i < fileInput.files.length; i++) {
            //Appending each file to FormData object
            formdata.append(fileInput.files[i].name, fileInput.files[i]);
        }
        //Creating an XMLHttpRequest and sending
        var xhr = new XMLHttpRequest();

           var url = '@Url.Action("Index","Home")';
        xhr.open('POST', url);
        xhr.send(formdata);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var result = xhr.responseText;

            }
        }
        return false;
    }
}
</script>


C#

public ActionResult Index()
{ 
   if (Request.Files.Count > 0)
   {
      var file = Request.Files[0];    
      if (file != null && file.ContentLength > 0)
      {
         var fileName = Path.GetFileName(file.FileName);
         var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
         file.SaveAs(path);
      }
    return View();

   }
}

这篇关于为什么MVC HttpPostedFileBase始终为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆