ASP.NET MVC实现文件上传

 1. 创建 files文件用于存放上传的文件
2.添加上传html

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>File</title>
</head>
<body>
    <div> 
        <form action="/File/Index" method="post" enctype="multipart/form-data">
            <input  name="file" type="file"/>
            <button type="submit">提交</button>
        </form>
    </div>
</body>
</html>

3. 后端接受上传文件

[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
    if(file != null)
    {
        string filePath = Server.MapPath("~/files/") + file.FileName; //获取文件路径
        file.SaveAs(filePath); //将文件保存在此路径中
        return Content("<script>alert('上传文件成功!')</script>");
    }
    return View("File");
}

 

posted @ 2024-06-28 09:50  龙卷风吹毁停车场  阅读(55)  评论(0)    收藏  举报