第一步,新建文件upload.aspx
第二步,在upload.aspx的设计页面里放入<asp:FileUpload ID="ImgUpload" runat="server" />控件和button控件,button控件的单击代码如下.
第三步,写代码,代码如下:
if (ImgUpload.FileName != null)
{
string ImgName = ImgUpload.FileName;
string ImgExtention = System.IO.Path.GetExtension(ImgName);
int ImgSize = ImgUpload.PostedFile.ContentLength;//此处取得的文件大小的单位是byte
string ImgPath = Server.MapPath("~/upload_files/works/");//此处是你的项目下的文件夹
string ImgUrl = "upload_files/works/" + ImgName;//This is for the saving in the sql.
if (ImgExtention == ".gif" || ImgExtention == ".GIF" || ImgExtention == ".jpg" || ImgExtention == ".JPG" || ImgExtention == ".jpeg" || ImgExtention == ".JPEG")
{
if (ImgSize / 1024 < 1024)//转换为kb
{
ImgUpload.PostedFile.SaveAs(ImgPath + ImgName);
ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('上传图片成功!');</script>");
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('图片大小不能超过1M!');</script>");
}
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('图片格式不正确,只支持.gif/.jpg/.jpeg格式类型的图片!');</script>");
}
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择要上传的图片!');</script>");
}
第二步,在upload.aspx的设计页面里放入<asp:FileUpload ID="ImgUpload" runat="server" />控件和button控件,button控件的单击代码如下.
第三步,写代码,代码如下:
if (ImgUpload.FileName != null)
{
string ImgName = ImgUpload.FileName;
string ImgExtention = System.IO.Path.GetExtension(ImgName);
int ImgSize = ImgUpload.PostedFile.ContentLength;//此处取得的文件大小的单位是byte
string ImgPath = Server.MapPath("~/upload_files/works/");//此处是你的项目下的文件夹
string ImgUrl = "upload_files/works/" + ImgName;//This is for the saving in the sql.
if (ImgExtention == ".gif" || ImgExtention == ".GIF" || ImgExtention == ".jpg" || ImgExtention == ".JPG" || ImgExtention == ".jpeg" || ImgExtention == ".JPEG")
{
if (ImgSize / 1024 < 1024)//转换为kb
{
ImgUpload.PostedFile.SaveAs(ImgPath + ImgName);
ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('上传图片成功!');</script>");
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('图片大小不能超过1M!');</script>");
}
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('图片格式不正确,只支持.gif/.jpg/.jpeg格式类型的图片!');</script>");
}
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择要上传的图片!');</script>");
}