//上传图片并且返回数据库路径
public void UploadFile(FileUpload File1, string FilePath, ref string UploadReturn)
{
if (IsAllowedExtension(File1.PostedFile.InputStream))
{
//设置图片名字随机数
Random randobj = new Random();
string FileRandom = DateTime.Now.ToString("yyyyMMddhhmmss") + randobj.Next(9999);
//获取扩展名
int ExtIndex = File1.PostedFile.FileName.LastIndexOf(".");
string ExtName = File1.PostedFile.FileName.Substring(ExtIndex);
//设置存储图片相对路径地址
string ServerFilePath = FilePath + FileRandom + ExtName;
File1.PostedFile.SaveAs(ServerFilePath);
//返回存储数据库地址
UploadReturn = FileRandom + ExtName;
}
else
{
//上传图片类型不合法!
UploadReturn = "";
}
}
//判断扩展名
public bool IsAllowedExtension(System.IO.Stream fs)
{
bool ret = false;
System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
string fileclass = "";
byte buffer;
try
{
buffer = r.ReadByte();
fileclass = buffer.ToString();
buffer = r.ReadByte();
fileclass += buffer.ToString();
}
catch
{
return false;
}
//r.Close();
//fs.Close();
/*文件扩展名说明
*4946/104116 txt
*7173 gif
*255216 jpg
*13780 png
*6677 bmp
*239187 txt,aspx,asp,sql
*208207 xls.doc.ppt
*6063 xml
*6033 htm,html
*4742 js
*8075 xlsx,zip,pptx,mmap,zip
*8297 rar
*01 accdb,mdb
*7790 exe,dll
*5666 psd
*255254 rdp
*10056 bt种子
*64101 bat
*4059 sgf
*/
String[] fileType = { "255216", "7173", "6677", "13780" };
String[] fileExtName = { "jpg", "gif", "bmp", "png" };
String fExt = "";
for (int i = 0; i < fileType.Length; i++)
{
if (fileclass == fileType[i])
{
fExt = fileExtName[i];
ret = true;
break;
}
}
//System.Web.HttpContext.Current.Response.Write(fExt);//可以在这里输出你不知道的文件类型的扩展名
return ret;
}
图片上传
最新推荐文章于 2023-12-19 19:57:44 发布