做这个项目时,我需要将图片上传到服务器进行保存,也就有了以后的几种尝试,先说我最先尝试的一种——ASP.NET自带的Fileupload控件
这个控件其实用起来非常简单,控件形状如下:
那么将直接以代码形式解释Fileupload用法
//图片上传云服务器
if (((FileUpload)DetailsView1.FindControl("FileUpload1")).PostedFile.ContentLength < 5000000) //这里是判断文件大小是否超出5000000(约5M)
{
string filefullname = ((FileUpload)DetailsView1.FindControl("FileUpload1")).FileName; //获取文件获取路径和文件名
string fillName = filefullname.Substring(filefullname.LastIndexOf("\\") + 1); //获取文件名
string type = filefullname.Substring(filefullname.LastIndexOf(".") + 1); //获取文件类型
if (type == "png" || type == "bmp" || type == "jpg" || type == "gif" || type == "PNG" ||
type == "JPG" || type == "BMP" || type == "GIF") //判断文件类型
{
//判断是否有该路径
string wantPath = Server.MapPath("../images/artices");
if (!Directory.Exists(wantPath))
Directory.CreateDirectory(wantPath); //若没有路径就创建新的路径
((FileUpload)DetailsView1.FindControl("FileUpload1")).SaveAs(Server.MapPath("../images/artices/") +
fillName); //上传服务器(获取服务器项目地址是Server.MapPath())
}
}