AJAX实现图片预览与上传及生成缩略图的方法
程序员文章站
2022-11-22 20:13:08
要实现功能,上传图片时可以预览,因还有别的文字,所以并不只上传图片,实现与别的文字一起保存,当然上来先上传图片,然后把路径和别的文字一起写入数据库;同时为 图片生成缩略图,...
要实现功能,上传图片时可以预览,因还有别的文字,所以并不只上传图片,实现与别的文字一起保存,当然上来先上传图片,然后把路径和别的文字一起写入数据库;同时为 图片生成缩略图,现只写上传图片方法,文字在ajax里直接传参数就可以了,若要上传多图,修改一下就可以了。
借鉴了网上资料,自己写了一下,并不需要再新加页面,只在一个页面里就ok啦。
js代码:
//ajax保存数据,后台方法里实现此方法 function savedata() { filename = document.getelementbyid("idfile").value; result =test_test_aspx.savedata(filename).value; if (result) { alert("保存成功!"); } return false; } //实现预览功能 function drawimage(imgd) { var prew = 118; var preh = 118; var image = new image(); 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内容改变时 function filechange(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; }
以下为前台代码:
<div class="cbs"> <div class="l"><label>图片:</label></div> <div> <input id="idfile" name="pic" type="file" runat="server" onchange="filechange(this.value);" /> </div> </div> <div class="cbs"> <div class="l"><label>预览:</label></div> <div> <img id="idimg" height="0" width="0" src="" alt="" onload="drawimage(this);" /> //实现预览 <img id="showimg" width="118" height="118" alt="" runat="server" style="display:none"/> //加这个主要是为了实现查看时显示图片,因为上面的(idimg)加上runat="server" 报错,如有好的方法可以留言 </div> </div>
以下为ajax方法:
[ajax.ajaxmethod()] public bool savedata(string filenamepath) { string serverfilename = ""; string sthumbfile = ""; string ssavepath = "~/files/"; int intthumbwidth = 118; int intthumbheight = 118; string sthumbextension = "thumb_"; try { //获取要保存的文件信息 fileinfo file = new fileinfo(filenamepath); //获得文件扩展名 string filenameext = file.extension; //验证合法的文件 if (checkfileext(filenameext)) { //生成将要保存的随机文件名 string filename = getfilename() + filenameext; //检查保存的路径 是否有/结尾 if (ssavepath.endswith("/") == false) ssavepath = ssavepath + "/"; //按日期归类保存 string datepath = datetime.now.tostring("yyyymm") + "/" + datetime.now.tostring("dd") + "/"; if (true) { ssavepath += datepath; } //获得要保存的文件路径 serverfilename = ssavepath + filename; //物理完整路径 string tofilefullpath = httpcontext.current.server.mappath(ssavepath); //检查是否有该路径 没有就创建 if (!directory.exists(tofilefullpath)) { directory.createdirectory(tofilefullpath); } //将要保存的完整文件名 string tofile = tofilefullpath + filename; ///创建webclient实例 webclient mywebclient = new webclient(); //设定windows网络安全认证 mywebclient.credentials = credentialcache.defaultcredentials; //要上传的文件 filestream fs = new filestream(filenamepath, filemode.open, fileaccess.read); //filestream fs = openfile(); binaryreader r = new binaryreader(fs); //使用uploadfile方法可以用下面的格式 //mywebclient.uploadfile(tofile, "put",filenamepath); byte[] postarray = r.readbytes((int)fs.length); stream poststream = mywebclient.openwrite(tofile, "put"); if (poststream.canwrite) { poststream.write(postarray, 0, postarray.length); } poststream.close(); //以上为原图 try { //原图加载 using (system.drawing.image sourceimage = system.drawing.image.fromfile(system.web.httpcontext.current.server.mappath(serverfilename))) { //原图宽度和高度 int width = sourceimage.width; int height = sourceimage.height; int smallwidth; int smallheight; //获取第一张绘制图的大小,(比较 原图的宽/缩略图的宽 和 原图的高/缩略图的高) if (((decimal)width) / height <= ((decimal)intthumbwidth) / intthumbheight) { smallwidth = intthumbwidth; smallheight = intthumbwidth * height / width; } else { smallwidth = intthumbheight * width / height; smallheight = intthumbheight; } //判断缩略图在当前文件夹下是否同名称文件存在 int file_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; } //缩略图保存的绝对路径 string smallimagepath = system.web.httpcontext.current.server.mappath(ssavepath) + sthumbfile; //新建一个图板,以最小等比例压缩大小绘制原图 using (system.drawing.image bitmap = new system.drawing.bitmap(smallwidth, smallheight)) { //绘制中间图 using (system.drawing.graphics g = 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, new system.drawing.rectangle(0, 0, smallwidth, smallheight), new system.drawing.rectangle(0, 0, width, height), system.drawing.graphicsunit.pixel ); } //新建一个图板,以缩略图大小绘制中间图 using (system.drawing.image bitmap1 = new system.drawing.bitmap(intthumbwidth, intthumbheight)) { //绘制缩略图 using (system.drawing.graphics g = system.drawing.graphics.fromimage(bitmap1)) { //高清,平滑 g.interpolationmode = system.drawing.drawing2d.interpolationmode.high; g.smoothingmode = system.drawing.drawing2d.smoothingmode.highquality; g.clear(color.black); int lwidth = (smallwidth - intthumbwidth) / 2; int bheight = (smallheight - intthumbheight) / 2; g.drawimage(bitmap, new rectangle(0, 0, intthumbwidth, intthumbheight), lwidth, bheight, intthumbwidth,intthumbheight, graphicsunit.pixel); g.dispose(); bitmap1.save(smallimagepath, system.drawing.imaging.imageformat.jpeg); return true; } } } } } catch { //出错则删除 system.io.file.delete(system.web.httpcontext.current.server.mappath(serverfilename)); return false; } } else { return false; } } catch (exception e) { return false; } } /// <summary> /// 检查是否为合法的上传文件 /// </summary> /// <param name="_fileext"></param> /// <returns></returns> private bool checkfileext(string _fileext) { string[] allowext = new string[] { ".gif", ".jpg", ".jpeg" }; for (int i = 0; i < allowext.length; i++) { if (allowext[i] == _fileext) { return true; } } return false; } //生成随机数文件名 public static string getfilename() { random rd = new random(); stringbuilder serial = new stringbuilder(); serial.append(datetime.now.tostring("yyyymmddhhmmssff")); serial.append(rd.next(0, 999999).tostring()); return serial.tostring(); }
以上就是小编为大家带来的ajax实现图片预览与上传及生成缩略图的方法的全部内容了,希望对大家有所帮助,多多支持~
上一篇: 煮豆浆要多长时间才能喝?
下一篇: 真实的历史上,曹操对司马懿是什么态度呢?