ASP.NET MVC 3 - 文件上传 [英] ASP.NET MVC 3 - File Upload

查看:75
本文介绍了ASP.NET MVC 3 - 文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET MVC 3应用程序。我需要在它实现文件上传动作。出于某种原因,当我发布我的形式,Request.Files集合为空。我已经能够通过设置断点来证实这一点。所以我知道我到达的行动。不过,我想不通为什么Request.Files集合为空。以下是我的相关HTML,AreaRegistration和控制器片断。

I have an ASP.NET MVC 3 application. I need to implement a file uploader action within it. For some reason, when I post my form, the Request.Files collection is empty. I have been able to confirm this by setting a breakpoint. So I know that I'm reaching the action. However, I can't figure out why the Request.Files collection is empty. Here are my relevant HTML, AreaRegistration, and Controller snippets.

的index.html

<form action="/files/upload/uniqueID" method="post" enctype="multipart/form-data">
    <div>Please choose a file to upload.</div>
    <div><input id="fileUpload" type="file" /></div>

    <div><input type="submit" value="upload" /></div>
</form>

MyAreaRegistration.cs

context.MapRoute(
  "FileUpload",
  "files/upload",
  new { action = "UploadFile", controller = "Uploader" }
);

UploaderController.cs

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadFile(int uniqueID)
{
  foreach (string file in Request.Files)
  {
    // I never get here :(
  }

  return View();
}

我没有对默认web.config文件进行任何更改。有一些设置,我需要补充的吗?我想不通,为什么Request.Files收集将是空的。是否有人可以帮助我吗?

I have not made any changes to the default web.config file. Is there some setting I need to add? I can't figure out why the Request.Files collection would be empty. Can someone please help me?

感谢你了!

推荐答案

您应该为你控制器和做这样的事情使用HttpPostedFileBase

You should use HttpPostedFileBase for you controller and do something like that

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) 
{

    if (file.ContentLength > 0) 
    {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/App_Data/"), fileName);
        file.SaveAs(path);
    }

    return RedirectToAction("Index");
}

和为视图

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

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

    <input type="submit" />
</form>

检查菲尔哈克博客在这里为这个问题:上传文件(或文件)的ASP.NET MVC

这篇关于ASP.NET MVC 3 - 文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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