asp.net上传图片的一个类源码,大家可以借用

2009年3月7日星期六

asp.net上传图片的一个类源码,大家可以借用

这是本人asp.net上传图片的一个类源码,大家可以借用,可以正常使用,,如果代码不符合你使用的要求,可以在此基础上进行改动,希望可以共同讨论。
///
/// Upload 的摘要说明
/// 用于上传图片,限制文件大小、格式等。
///

///

public class UploadResult
{
public string UpMsg = string.Empty;
public byte[] imagefile = new byte[0];
public bool isSuccess = false;
public UploadResult()
{
}


}
public class Upload
{
public Upload()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
///
/// 图片上传函数
///

/// 上传控件
/// 最大体积
/// 形式为.jpg.jpeg
/// 上传结果类
public static UploadResult ImageUpload(System.Web.UI.WebControls.FileUpload FileUper ,int MaxSize,string Typestr)
{
UploadResult imgresult=new UploadResult();
Stream objStream;
string filename,subname;

int intDocLen =FileUper.PostedFile.ContentLength;
filename=FileUper.PostedFile.FileName;
if (intDocLen>0 && filename.Length>0)
{
subname=Path.GetExtension(filename).ToLower();

if(Typestr.IndexOf(subname)>=0)
{

if (intDocLen>(MaxSize*1024))
{
imgresult.UpMsg="图片大小超过了"+MaxSize.ToString()+"k,请调整后再上传图片";
}
else
{
imgresult.imagefile = new byte[intDocLen];//用图片的长度来初始化一个字节数组存储临时的图片文件



   objStream =FileUper.PostedFile.InputStream; //建立文件流对象

   //文件保存到缓存
   //缓存将保存到数据库
objStream.Read(imgresult.imagefile, 0, intDocLen);//读取图片数据到临时存储体imagefile,0为数据指针位置,fileLength为数据长度


if (imgresult.imagefile.Length>1000)
{
imgresult.isSuccess=true;
imgresult.UpMsg="图片上传成功!";
//HttpContext.Current.Session["CurpicCar"]=Docbuffer;
}

}
}
else
{
imgresult.UpMsg="图片格式不正确!请上传大小在"+MaxSize.ToString()+"k以内的"+Typestr+"图片";
}
}

return imgresult;
}
}

0 评论:

发表评论