ASP.NET MVC : 文件上传

前端页面显示

必须要在form里进行标记 enctype="multipart/form-data"

@using (Html.BeginForm("AjaxUpload", "DownLoad", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.TextBox("fileData", "", new { type = "file", size = "25" })
        <input type="submit" value="确定" />
    }

 

后台代码

在Action中通过HttpPostedFileBase参数可直接获取上传文件内容:

 public void AjaxUpload(HttpPostedFileBase fileData)
        {
            string filename = fileData.FileName;
            string path = Server.MapPath("~/upload");
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            fileData.SaveAs(path+"/"+filename);
 
            //Stream s = fileData.InputStream;
            //byte[] buffer = new byte[s.Length];
            //s.Read(buffer, 0, buffer.Length);  //将流的内容读到缓冲区
            //FileStream fs = new FileStream("文件路径", FileMode.OpenOrCreate, FileAccess.Write);
            //fs.Write(buffer, 0, buffer.Length);
            //fs.Flush();
            //fs.Close();
        }

 

HttpPostedFileBase对象有:

ContentType属性

可以检测文件类型。

为了安全考虑,一般需要对上传文件的类型进行检查,注意这时候不要仅从文件后缀

contentType检查文件类型:image/*

image/png
image/gif
image/jpeg

FileName属性

可获得文件名称

SaveAs()方法

可将上传文件存放到指定位置。

PS:绝大多数情况,我们都不会(虽然可以)把文件直接存放到数据库中。

根据需求来规划好文件路径

文章转载自:快速开发平台– 云微平台
地址:https://www.hocode.com/

 

posted @ 2022-02-12 16:47  码上的飞鱼  阅读(488)  评论(0)    收藏  举报