[Asp.net] MVC5 上传文件

控制器名 UploadTest

里面新两个Action, 分别为Upload()和SaveAs()

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace UploadFileTest.Controllers
{
    public class UploadTestController : Controller
    {
        // GET: UploadTest
        public ActionResult Index()
        {
            return View();
        }


        //这个view是用来选择上传文件的
        public ActionResult Upload()
        {
            return View();

        }

        //这个action是用来接收文件并保存在服务器上
        [HttpPost]
       public ActionResult SaveAs(HttpPostedFileBase MyFile)
        {
            //得到的名字是文件在本地机器的绝对路径
            var strLocalFullPathName = MyFile.FileName;
            //提取出单独的文件名,不需要路径
            var strFileName = Path.GetFileName(strLocalFullPathName);
            //定义服务器的文件夹,用来保存文件
            var strServerFilePath = Server.MapPath("/docs/");
            //将接收到文件保存在服务器指定上当
            MyFile.SaveAs(Path.Combine(strServerFilePath,strFileName));

            //下面只是用来显示一些相关字符串做测试用
            ViewBag.strLocalFullPathName = strLocalFullPathName;
            ViewBag.strFileName = strFileName;
            ViewBag.strServerFilePath = strServerFilePath;

            return View();

        }

    }
}

Upload()方法的View视图,要为form添加一个属性: 

enctype="multipart/form-data"

注意: 红色部分,第一是要用name的属性,第二是这个名字要与SaveAs()的参数名相同

name="MyFile" />

SaveAs()方法的View视图,只是查看相关的字符串

@ViewBag.strLocalFullPathName
@ViewBag.strFileName
@ViewBag.strServerFilePath


你可能感兴趣的:(ASP.NET,MVC)