上传图片
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
//WEB目录new文件名upload.aspx.cs
public partial class new_upload : System.Web.UI.Page
{
private const string strFileTypeAllow = "|image/pjpeg|image/gif|image/png|image/bmp|image/x-png|";//允许的文件类型
private const long lngFileMaxLenthAllow = 1048576;//最大的文件大小
private const string strUploadPath = "UploadFiles/";//路径
protected string strChangeSingleNum(string strNum)
{
if (strNum.Length < 2)
return "0" + strNum;
else
return strNum;
}
private string strChangeSingleNum(int intNum)
{
string strNum = intNum.ToString();
if (strNum.Length < 2)
return ("0" + strNum);
else
return strNum;
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
HttpPostedFile hpfRcvFile = inFile.PostedFile;
string strLocalFileName;
if (strFileTypeAllow.IndexOf("|" + hpfRcvFile.ContentType + "|") >= 0 && hpfRcvFile.ContentLength <= lngFileMaxLenthAllow)
{
//取得扩展名
string[] strTemp = hpfRcvFile.FileName.Split('.');
string strExtName = strTemp[strTemp.Length - 1];
//获取随机字符串做文件名
DateTime datNow = DateTime.Now;
string strYear = datNow.Year.ToString();
string strMonth = datNow.Month.ToString();
string strDay = datNow.Day.ToString();
strMonth = strChangeSingleNum(strMonth);
strDay = strChangeSingleNum(strDay);
Random ranMy = new Random();
strLocalFileName=strYear+strMonth+strDay+ranMy.Next(1000000,9999999).ToString()+"."+strExtName;
//按照设定保存文件
hpfRcvFile.SaveAs(Server.MapPath(strUploadPath)+strLocalFileName);
//显示成功信息
Response.Redirect("thankyou.aspx");
}
else
//显示错误信息
Response.Redirect("showError.aspx?ErrMsg=非法的文件类型或文件大小不合适!");
inFile.PostedFile.SaveAs(Server.MapPath("temp.jpg"));
Response.Write("文件"+inFile.PostedFile.FileName + "上传成功!大小:"+inFile.PostedFile.ContentLength.ToString()+"<br>传输类型:"+inFile.PostedFile.ContentType);
}
}