AJAX实现图片预览与上传及生成缩略图的方法
要实现功能,上传图片时可以预览,因还有别的文字,所以并不只上传图片,实现与别的文字一起保存,当然上来先上传图片,然后把路径和别的文字一起写入数据库;同时为图片生成缩略图,现只写上传图片方法,文字在ajax里直接传参数就可以了,若要上传多图,修改一下就可以了。
借鉴了网上资料,自己写了一下,并不需要再新加页面,只在一个页面里就OK啦。
JS代码:
//ajax保存数据,后台方法里实现此方法
functionSaveData(){
filename=document.getElementById("idFile").value;
result=test_test_aspx.SaveData(filename).value;
if(result){
alert("保存成功!");
}
returnfalse;
}
//实现预览功能
functionDrawImage(ImgD){
varpreW=118;
varpreH=118;
varimage=newImage();
image.src=ImgD.src;
if(image.width>0&&image.height>0){
flag=true;
if(image.width/image.height>=preW/preH){
if(image.width>preW){
ImgD.width=preW;
ImgD.height=(image.height*preW)/image.width;
}
else{
ImgD.width=image.width;
ImgD.height=image.height;
}
ImgD.alt=image.width+"x"+image.height;
}
else{
if(image.height>preH){
ImgD.height=preH;
ImgD.width=(image.width*preH)/image.height;
}
else{
ImgD.width=image.width;
ImgD.height=image.height;
}
ImgD.alt=image.width+"x"+image.height;
}
}
}
//当idFile内容改变时
functionFileChange(Value){
flag=false;
document.getElementById("showImg").style.display="none";
document.getElementById("idImg").width=10;
document.getElementById("idImg").height=10;
document.getElementById("idImg").alt="";
document.getElementById("idImg").src=Value;
}
以下为前台代码:
<divclass="cbs"> <divclass="l"><label>图片:</label></div> <div> <inputid="idFile"name="pic"type="file"runat="server"onchange="FileChange(this.value);"/> </div> </div> <divclass="cbs"> <divclass="l"><label>预览:</label></div> <div> <imgid="idImg"height="0"width="0"src=""alt=""onload="DrawImage(this);"/>//实现预览 <imgid="showImg"width="118"height="118"alt=""runat="server"style="display:none"/>//加这个主要是为了实现查看时显示图片,因为上面的(idImg)加上runat="server"报错,如有好的方法可以留言 </div> </div>
以下为AJAX方法:
[Ajax.AjaxMethod()]
publicboolSaveData(stringfileNamePath)
{
stringserverFileName="";
stringsThumbFile="";
stringsSavePath="~/Files/";
intintThumbWidth=118;
intintThumbHeight=118;
stringsThumbExtension="thumb_";
try
{
//获取要保存的文件信息
FileInfofile=newFileInfo(fileNamePath);
//获得文件扩展名
stringfileNameExt=file.Extension;
//验证合法的文件
if(CheckFileExt(fileNameExt))
{
//生成将要保存的随机文件名
stringfileName=GetFileName()+fileNameExt;
//检查保存的路径是否有/结尾
if(sSavePath.EndsWith("/")==false)sSavePath=sSavePath+"/";
//按日期归类保存
stringdatePath=DateTime.Now.ToString("yyyyMM")+"/"+DateTime.Now.ToString("dd")+"/";
if(true)
{
sSavePath+=datePath;
}
//获得要保存的文件路径
serverFileName=sSavePath+fileName;
//物理完整路径
stringtoFileFullPath=HttpContext.Current.Server.MapPath(sSavePath);
//检查是否有该路径没有就创建
if(!Directory.Exists(toFileFullPath))
{
Directory.CreateDirectory(toFileFullPath);
}
//将要保存的完整文件名
stringtoFile=toFileFullPath+fileName;
///创建WebClient实例
WebClientmyWebClient=newWebClient();
//设定windows网络安全认证
myWebClient.Credentials=CredentialCache.DefaultCredentials;
//要上传的文件
FileStreamfs=newFileStream(fileNamePath,FileMode.Open,FileAccess.Read);
//FileStreamfs=OpenFile();
BinaryReaderr=newBinaryReader(fs);
//使用UploadFile方法可以用下面的格式
//myWebClient.UploadFile(toFile,"PUT",fileNamePath);
byte[]postArray=r.ReadBytes((int)fs.Length);
StreampostStream=myWebClient.OpenWrite(toFile,"PUT");
if(postStream.CanWrite)
{
postStream.Write(postArray,0,postArray.Length);
}
postStream.Close();
//以上为原图
try
{
//原图加载
using(System.Drawing.ImagesourceImage=System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath(serverFileName)))
{
//原图宽度和高度
intwidth=sourceImage.Width;
intheight=sourceImage.Height;
intsmallWidth;
intsmallHeight;
//获取第一张绘制图的大小,(比较原图的宽/缩略图的宽和原图的高/缩略图的高)
if(((decimal)width)/height<=((decimal)intThumbWidth)/intThumbHeight)
{
smallWidth=intThumbWidth;
smallHeight=intThumbWidth*height/width;
}
else
{
smallWidth=intThumbHeight*width/height;
smallHeight=intThumbHeight;
}
//判断缩略图在当前文件夹下是否同名称文件存在
intfile_append=0;
sThumbFile=sThumbExtension+System.IO.Path.GetFileNameWithoutExtension(fileName)+fileNameExt;
while(System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(sSavePath+sThumbFile)))
{
file_append++;
sThumbFile=sThumbExtension+System.IO.Path.GetFileNameWithoutExtension(fileName)+
file_append.ToString()+fileNameExt;
}
//缩略图保存的绝对路径
stringsmallImagePath=System.Web.HttpContext.Current.Server.MapPath(sSavePath)+sThumbFile;
//新建一个图板,以最小等比例压缩大小绘制原图
using(System.Drawing.Imagebitmap=newSystem.Drawing.Bitmap(smallWidth,smallHeight))
{
//绘制中间图
using(System.Drawing.Graphicsg=System.Drawing.Graphics.FromImage(bitmap))
{
//高清,平滑
g.InterpolationMode=System.Drawing.Drawing2D.InterpolationMode.High;
g.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.Clear(Color.Black);
g.DrawImage(
sourceImage,
newSystem.Drawing.Rectangle(0,0,smallWidth,smallHeight),
newSystem.Drawing.Rectangle(0,0,width,height),
System.Drawing.GraphicsUnit.Pixel
);
}
//新建一个图板,以缩略图大小绘制中间图
using(System.Drawing.Imagebitmap1=newSystem.Drawing.Bitmap(intThumbWidth,intThumbHeight))
{
//绘制缩略图
using(System.Drawing.Graphicsg=System.Drawing.Graphics.FromImage(bitmap1))
{
//高清,平滑
g.InterpolationMode=System.Drawing.Drawing2D.InterpolationMode.High;
g.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.Clear(Color.Black);
intlwidth=(smallWidth-intThumbWidth)/2;
intbheight=(smallHeight-intThumbHeight)/2;
g.DrawImage(bitmap,newRectangle(0,0,intThumbWidth,intThumbHeight),lwidth,bheight,intThumbWidth,intThumbHeight,GraphicsUnit.Pixel);
g.Dispose();
bitmap1.Save(smallImagePath,System.Drawing.Imaging.ImageFormat.Jpeg);
returntrue;
}
}
}
}
}
catch
{
//出错则删除
System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath(serverFileName));
returnfalse;
}
}
else
{
returnfalse;
}
}
catch(Exceptione)
{
returnfalse;
}
}
///<summary>
///检查是否为合法的上传文件
///</summary>
///<paramname="_fileExt"></param>
///<returns></returns>
privateboolCheckFileExt(string_fileExt)
{
string[]allowExt=newstring[]{".gif",".jpg",".jpeg"};
for(inti=0;i<allowExt.Length;i++)
{
if(allowExt[i]==_fileExt){returntrue;}
}
returnfalse;
}
//生成随机数文件名
publicstaticstringGetFileName()
{
Randomrd=newRandom();
StringBuilderserial=newStringBuilder();
serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff"));
serial.Append(rd.Next(0,999999).ToString());
returnserial.ToString();
}
以上就是小编为大家带来的AJAX实现图片预览与上传及生成缩略图的方法的全部内容了,希望对大家有所帮助,多多支持毛票票~