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

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

问题描述

(前言:这个问题是关于 ASP.NET MVC 3.0 其中 于 2011 年发布,不是关于 ASP.NET Core 3.0 于 2019 年发布的)

(Preface: this question is about ASP.NET MVC 3.0 which was released in 2011, it is not about ASP.NET Core 3.0 which was released in 2019)

我想在 asp.net mvc 中上传文件.如何使用 html input file 控件上传文件?

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天全站免登陆