1.在ASP.NET页面中添加input标签,设置type属性为“file”,name属性为“file”:
<input type="file" name="file" />
2.在页面的后台代码中,使用HttpPostedFile类来获取上传文件:
HttpPostedFile file = Request.Files["file"];
3.检查文件是否存在,以及文件的大小:
if (file != null && file.ContentLength > 0)
4.获取上传文件的文件类型,并检查文件类型是否为Excel文件:
string fileType = file.ContentType; if (fileType == "application/vnd.ms-excel" || fileType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
5.使用SaveAs()方法保存上传的文件:
string fileName = Path.GetFileName(file.FileName); string physicalPath = Server.MapPath("~/Uploads/" + fileName);
file.SaveAs(physicalPath);