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

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

问题描述

我要上传文件中的 asp.net-MVC 。我如何使用HTML 输入文件控制上传的文件?

I want to upload file in asp.net-mvc. How can I upload the file using html input file control?

推荐答案

您不使用文件输入控制。服务器端控件未在ASP.NET MVC使用。签出以下博客帖子它说明了如何在ASP实现这一目标。 NET MVC。

You don't use a file input control. Server side controls are not used in ASP.NET MVC. Checkout the following blog post which illustrates how to achieve this in ASP.NET MVC.

所以,你会通过创建一个HTML表单,其中将包括文件输入启动:

So you would start by creating an HTML form which would contain a file input:

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="file" />
    <input type="submit" value="OK" />
}

然后你将有一个控制器来处理上传:

and then you would have a controller to handle the upload:

public class HomeController : Controller
{
    // This action renders the form
    public ActionResult Index()
    {
        return View();
    }

    // This action handles the form POST and the upload
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        // Verify that the user selected a file
        if (file != null && file.ContentLength > 0) 
        {
            // extract only the filename
            var fileName = Path.GetFileName(file.FileName);
            // store the file inside ~/App_Data/uploads folder
            var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
            file.SaveAs(path);
        }
        // redirect back to the index action to show the form once again
        return RedirectToAction("Index");        
    }
}

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

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