最近做的一个项目中,用到了jspsmartUpload的jar包,将图片上传到Tomcat上面,我本人也是在学习阶段,跟大家分享一下。
我们下载一个jspSmart.zip,解压后将jspsmart.jar导入到myclipse中,这里我们也可以直接下载jspSmartUpload,用它的源码也是可以的。
如图:
或者是这样的:
这里我用的是第二种方式:
之后,我们要写WebImage.jsp界面:
<span style="font-size:18px;"><%@ page language="java" contentType="text/html;charset=GBK" %> <% String strUpload=""; String strFilename=""; String strXx=""; String jgdm=""; strUpload=request.getParameter("uploadpath"); strFilename=request.getParameter("filename"); strXx=request.getParameter("xx"); jgdm=request.getParameter("jgdm");//获取机构代码 String strtext=request.getParameter("text"); if(strtext==null)strtext="0"; if(strXx==null) { strXx=""; } %> <HTML> <HEAD> <meta http-equiv="Content-Type" content="text/html; charset=GBK"> <style type="text/css"> body, a, table, div, span, td, th, input, select{font:9pt;font-family: "宋体", Verdana, Arial, Helvetica, sans-serif;} body {padding:5px} </style> <script language="JavaScript" src="/UploadControl/dialog/dialog.js"></script> <script language="JavaScript" src="/UploadControl/dialog/news.js"></script> <BODY onLoad="InitDocument()"> <table border=0 cellpadding=0 cellspacing=0 align=center> <tr> <td> <fieldset> <legend>图片上传</legend> <table border=0 cellpadding=0 cellspacing=0 width="100%"> <tr> <td colspan=5 height=5></td> </tr> <%if(strtext.equals("1")){%> <tr> <td height=5> </td> <td height=5 align="right">图片描述:</td> <td height=5> </td> <td height=5><input name="d_info" type=text id="d_info" style="width:243px" value="" size=30></td> <td height=5> </td> </tr> <%} else { out.print("<input type=hidden name=\"d_info\" id=\"d_info\" value=\"\">"); }%> <tr> <td width=7></td> <td width=54 align=right onClick="RadioClick('file')" height="7"><input type=radio id="d_checkfromfile" value="1" onClick="RadioClick('file')"></td> <td width=5></td> <td valign="middle"> <Script Language=JavaScript> document.write('<iframe id=d_file frameborder=0 src="../uploadfile.jsp?type=image&style=CoolBlue&uploadpath=<%=strUpload%>&xx=<%=strXx%>&upload=1&jgdm=<%=jgdm%>" width="100%" height="32" scrolling=none></iframe>'); </Script> </td> <td width=7></td> </tr> <tr> <td colspan=5 height=5></td> </tr> <tr style="display:none"> <td width=7></td> <td width=54 align=right onClick="RadioClick('url')"><input type=radio id="d_checkfromurl" value="1" onClick="RadioClick('url')">网络:</td> <td width=5></td> <td><input name="text" type=text id="d_fromurl" style="width:243px" value="" size=30></td> <td width=7></td> </tr> </table> </fieldset></td> </tr> <tr><td height=5></td></tr> <tr><td> <table width="100%"> <tr> <td>上传图片为jpg格式文件,分辨率200*200以上,大小不超过3M。</td> </tr> <tr> <td align="center"> <!-- <input name="submit" type=submit id=Ok onClick="ok()" value='确定'> --> <input name="button" type=button onClick="window.close();" value='取消'></td> </tr> </table> </td></tr> </table> <div id=divProcessing style="width:200px;height:30px;position:absolute;left:70px;top:20px;display:none"> <table border=0 cellpadding=0 cellspacing=1 bgcolor="#000000" width="100%" height="100%"><tr><td bgcolor=#3A6EA5><marquee align="middle" behavior="alternate" scrollamount="5"><font color=#FFFFFF>...图片上传中...请等待...</font></marquee></td></tr></table> </div> <div id=divProcessing2></div> </body> </html> </span>
我们在uploadfile.jsp界面:
<span style="font-size:18px;"><%@ page language="java" contentType="text/html;charset=GBK" pageEncoding="GBK" import="java.util.*,com.jspsmart.upload.*,net.iesun.util.*" errorPage="" %> <% String strUpload,strFilename,xx,jgdm,sl,rootdir,retfun; strUpload=request.getParameter("uploadpath"); if(strUpload==null)strUpload=""; if(strUpload.equals(""))strUpload="/upload"; String rootpath=config.getServletContext().getRealPath("/"); rootdir=request.getParameter("rootdir"); rootdir="upload/advertise/"; if(rootdir==null)rootdir=""; if(rootdir.equals(""))rootdir="LOGOIMAGEPATH"; rootdir=rootdir.toUpperCase(); if(rootdir.equals("LOGOIMAGEPATH")||rootdir.equals("PROIMAGEPATH")) { rootpath=Ini.getDBValue(rootdir,rootpath); } /* rootdir "ROOT" "LOGOIMAGEPATH" logo.jsp stock.jsp teamBuy.jsp WebImage.jsp "PROIMAGEPATH" upload.jsp //Ini.getDBValue() */ sl=request.getParameter("sl"); if(sl==null)sl="0"; retfun=request.getParameter("retfun"); if(retfun==null)retfun=""; xx=request.getParameter("xx"); if(xx==null)xx=""; jgdm=String.valueOf(request.getParameter("jgdm"));//获取机构代码 if(jgdm.equals("null"))jgdm=""; strFilename=String.valueOf(Pub.getTimeInMillis(null)); strFilename=strFilename+xx;//文件名 String filename=""; String issave = request.getParameter("issave"); if(issave==null)issave="0"; if(issave.equals("1")) { filename=Images.upload(rootpath,strUpload,strFilename,pageContext); if(filename.indexOf(":")>0){ out.println("<script language=javascript>alert('"+filename+"');parent.UploadError(\"提示:\\n\\n"+filename+"\");</script>"); } else { if(sl.equals("1")) { String ext=Images.getFileExt(filename); String sSaveFileName=strFilename+"_sl"; //System.out.println(sSaveFileName); //System.out.println(rootpath+"/"+strUpload+"/"+strFilename+"."+ext); //System.out.println(rootpath+"/"+strUpload+"/"+sSaveFileName+"."+ext); Images.ResizeImage(rootpath+"/"+strUpload+"/"+strFilename+"."+ext,rootpath+"/"+strUpload+"/"+sSaveFileName+"."+ext,800,0); filename=sSaveFileName+"."+ext; } if(!retfun.equals("")) { out.println("<script language=javascript>var flag = window.opener."+retfun+"('"+filename+"');window.close();</script>"); } out.println("<script language=javascript>"); out.print("parent.UploadSaved('"); out.print(filename); out.print("');var obj=parent.dialogArguments.dialogArguments;if (!obj) obj=parent.dialogArguments;try{obj.addUploadFile('"); out.print(filename); out.print("', '"); out.print(filename); out.print("', '"); out.print(strUpload); out.print("');} catch(e){}"); out.println(";history.back()</script>"); } } %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title></title> <script language=javascript> function CheckUploadForm() { if (document.getElementById("upfile").value=="") { alert('选择一个上传文件!'); return false; } return true; } function check(form) { document.myform.submit(); } </script> <style type="text/css"> body {padding:0px;margin:0px;overflow-x:hidden;overflow-y:hidden;} </style> <script language="JavaScript" src="dialog/dialog.js"> </script> </head> <body> <div> <form name="myform" id="myform" method="post" action="/UploadControl/uploadfile.jsp?issave=1&jgdm=<%=jgdm%>&xx=<%=xx%>&uploadpath=<%=strUpload%>&sl=<%=sl%>&retfun=<%=retfun%>&rootdir=<%=rootdir%>" id="form1" enctype="multipart/form-data"> <div class="uploaddiv"> <input type="file" name="upfile" id="upfile" title="选择文件" style="width:170px" /><input type="submit" name="btnUpload" value="上 传" id="btnUpload" onclick="check(this.form)"/> <!-- <input name="button" type=button onClick="window.close();" value='取消'></td> --> </div> </form> </div> </body> </html></span>
uploadfile文件会将文件提交给net.iesun.util.Images类:
<span style="font-size:18px;">package net.iesun.util; import java.io.*; import java.text.SimpleDateFormat; import java.util.*; import java.awt.*; import java.awt.image.*; import java.awt.color.*; import javax.imageio.*; import javax.imageio.stream.*; import javax.imageio.metadata.*; import javax.servlet.jsp.PageContext; import org.w3c.dom.*; import java.awt.Rectangle; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.PageContext; import com.jspsmart.upload.File; import com.jspsmart.upload.SmartUpload; public class Images { public static String upload(String rootdir,String sPath,String FileName,PageContext pagecontext) { if(sPath==null)sPath="/upload"; if(sPath.equals(""))sPath="/upload"; if(FileName==null)FileName=""; if(rootdir.equals(""))rootdir=pagecontext.getServletContext().getRealPath("/"); String rpath=rootdir+"/"+sPath; java.io.File f = new java.io.File(rpath); if(!f.exists())f.mkdirs(); rpath=f.getPath(); try { SmartUpload mySmartUpload = new SmartUpload(); mySmartUpload.initialize(pagecontext); //mySmartUpload.initialize(config, request, response); mySmartUpload.setMaxFileSize(20480 * 1024); mySmartUpload.setAllowedFilesList("jpg,JPG,gif,GIF,png,PNG,jpeg,JPEG,bmp,BMP,tif,TIF,tiff,TIFF,swf,SWF,flv,FLV,doc,DOC,txt,TXT,xls,CLS,csv,CSV,ppt,PPT,zip,ZIP,rar,RAR"); mySmartUpload.upload(); File myFile = mySmartUpload.getFiles().getFile(0); if (!myFile.isMissing()) { if(FileName.equals(""))FileName=myFile.getFileName(); if(FileName.equals("")) { Date currTime = new Date(); SimpleDateFormat formatter2 = new SimpleDateFormat("yyyyMMddhhmmssSSS", Locale.US); FileName = new String((formatter2.format(currTime)).getBytes("iso-8859-1")); } String ext = myFile.getFileExt(); FileName = FileName + "." + ext; myFile.saveAs(rpath + "/" + FileName,mySmartUpload.SAVE_AUTO); } //response.sendRedirect("/uploadimage.jsp?Picurl="+ FileName + "&step=2"); } catch (Exception e) { e.printStackTrace(); return "ERR:"+e.getMessage(); } return FileName; } /** * 获取文件扩展名 * @param file * @return */ public static String getFileExt(String fileName) { if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) { return fileName.substring(fileName.lastIndexOf(".") + 1); } else { return ""; } } public static void ResizeImage(String SourceFile,String TargetFile,int nw,int nh){ try { //System.out.println("生成缩略图源文件"+SourceFile); java.io.File file = new java.io.File(SourceFile); //读入文件 if(!file.exists())return; BufferedImage img=null; try { img=javax.imageio.ImageIO.read(file); } catch(Exception e) { img=readImage(file); } int h = img.getHeight(); int w = img.getWidth(); //System.out.println("生成目标缩略图"+TargetFile); FileOutputStream out=new FileOutputStream(TargetFile); //输出到文件流 if(nw==0&&nh==0)nw=80; if(nw==0)nw=w*nw/h; if(nh==0)nh=h*nw/w; //java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); BufferedImage dest = new BufferedImage(nw, nh,BufferedImage.TYPE_INT_RGB);//TYPE_4BYTE_ABGR); dest.getGraphics().drawImage(img,0,0,nw, nh,null); ImageIO.write(dest, "jpg", out); out.close(); /* JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(dest); //近JPEG编码 out.close(); */ } catch(Exception e) { e.printStackTrace(); System.out.println("生成缩略图bug"+e.getMessage()); } } // extract metadata public static BufferedImage readImage(java.io.File file) throws IOException { // Get an ImageReader. try { ImageInputStream input = ImageIO.createImageInputStream(file); Iterator readers = ImageIO.getImageReaders(input); if (readers == null || !readers.hasNext()) { return null; } ImageReader reader = (ImageReader) readers.next(); reader.setInput(input); String format = reader.getFormatName(); if ("JPEG".equalsIgnoreCase(format) || "JPG".equalsIgnoreCase(format)) { try { IIOMetadata metadata = reader.getImageMetadata(0); String metadataFormat = metadata.getNativeMetadataFormatName(); IIOMetadataNode iioNode = (IIOMetadataNode) metadata.getAsTree(metadataFormat); NodeList children = iioNode.getElementsByTagName("app14Adobe"); if (children.getLength() > 0) { try { iioNode = (IIOMetadataNode) children.item(0); int transform = Integer.parseInt(iioNode.getAttribute("transform")); Raster raster = reader.readRaster(0, reader.getDefaultReadParam()); if (input != null) { input.close(); } reader.dispose(); return createJPEG4(raster, transform); } catch (Exception e) { // TODO Auto-generated catch block //log.error(e); } } } catch (Exception e) { // TODO Auto-generated catch block // log.error(e); // LogWriter.log(file.getPath()); } } } catch (NumberFormatException e) { // TODO Auto-generated catch block return null; } return null; } /** * * Java's ImageIO can't process 4-component images * * and Java2D can't apply AffineTransformOp either, * * so convert raster data to RGB. * * Technique due to MArk Stephens. * * Free for any use. * */ private static BufferedImage createJPEG4(Raster raster, int xform) { try { int w = raster.getWidth(); int h = raster.getHeight(); byte[] rgb = new byte[w * h * 3]; // if (Adobe_APP14 and transform==2) then YCCK else // CMYK if (xform == 2) { // YCCK -- // Adobe float[] Y = raster.getSamples(0, 0, w, h, 0, (float[]) null); float[] Cb = raster.getSamples(0, 0, w, h, 1, (float[]) null); float[] Cr = raster.getSamples(0, 0, w, h, 2, (float[]) null); float[] K = raster.getSamples(0, 0, w, h, 3, (float[]) null); for (int i = 0, imax = Y.length, base = 0; i < imax; i++, base += 3) { float k = 220 - K[i], y = 255 - Y[i], cb = 255 - Cb[i], cr = 255 - Cr[i]; double val = y + 1.402 * (cr - 128) - k; val = (val - 128) * .65f + 128; rgb[base] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5); val = y - 0.34414 * (cb - 128) - 0.71414 * (cr - 128) - k; val = (val - 128) * .65f + 128; rgb[base + 1] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5); val = y + 1.772 * (cb - 128) - k; val = (val - 128) * .65f + 128; rgb[base + 2] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5); } } else { // assert xform==0: xform; // CMYK int[] C = raster.getSamples(0, 0, w, h, 0, (int[]) null); int[] M = raster.getSamples(0, 0, w, h, 1, (int[]) null); int[] Y = raster.getSamples(0, 0, w, h, 2, (int[]) null); int[] K = raster.getSamples(0, 0, w, h, 3, (int[]) null); for (int i = 0, imax = C.length, base = 0; i < imax; i++, base += 3) { int c = 255 - C[i]; int m = 255 - M[i]; int y = 255 - Y[i]; int k = 255 - K[i]; float kk = k / 255f; rgb[base] = (byte) (255 - Math.min(255f, c * kk + k)); rgb[base + 1] = (byte) (255 - Math.min(255f, m * kk + k)); rgb[base + 2] = (byte) (255 - Math.min(255f, y * kk + k)); } } // from other image types we know InterleavedRaster's can be // manipulated by AffineTransformOp, so create one of those. raster = Raster.createInterleavedRaster(new DataBufferByte(rgb, rgb.length), w, h, w * 3, 3, new int[]{0, 1, 2}, null); ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); ColorModel cm = new ComponentColorModel(cs, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); return new BufferedImage(cm, (WritableRaster) raster, true, null); } catch (Exception e) { // TODO Auto-generated catch block //log.error(e); return null; } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub //ResizeImage("C:\\aaa.jpg","C:\\rgb.jpg",30,0); //ResizeImage("C:\\111.jpg","C:\\cmyk.jpg",30,0); String sss="ERR:asdfasdfasfd"; if(sss.indexOf(":")>0)System.out.println(sss); } } </span>
所有的图片都会上传到,upload文件目录下。这个参数也是可以变化的。
我们发出的请求:http://localhost:8080/UploadControl/dialog/stock.jsp?uploadpath=upload/purchase/&time=Sat%20Sep%2026%2020:51:29%20CST%202015
提交的方法是这样的:
<span style="font-size:18px;"> SmartUpload mySmartUpload = new SmartUpload(); mySmartUpload.initialize(pagecontext); //mySmartUpload.initialize(config, request, response); mySmartUpload.setMaxFileSize(20480 * 1024); mySmartUpload.setAllowedFilesList("jpg,JPG,gif,GIF,png,PNG,jpeg,JPEG,bmp,BMP,tif,TIF,tiff,TIFF,swf,SWF,flv,FLV,doc,DOC,txt,TXT,xls,CLS,csv,CSV,ppt,PPT,zip,ZIP,rar,RAR"); mySmartUpload.upload(); File myFile = mySmartUpload.getFiles().getFile(0); if (!myFile.isMissing()) { if(FileName.equals(""))FileName=myFile.getFileName(); if(FileName.equals("")) { Date currTime = new Date(); SimpleDateFormat formatter2 = new SimpleDateFormat("yyyyMMddhhmmssSSS", Locale.US); FileName = new String((formatter2.format(currTime)).getBytes("iso-8859-1")); } String ext = myFile.getFileExt(); FileName = FileName + "." + ext; myFile.saveAs(rpath + "/" + FileName,mySmartUpload.SAVE_AUTO); } ; } catch (Exception e) { e.printStackTrace(); return "ERR:"+e.getMessage(); } return FileName;</span>
提交路径为:
<span style="font-size:18px;"> if(sPath==null)sPath="/upload"; if(sPath.equals(""))sPath="/upload"; if(FileName==null)FileName=""; if(rootdir.equals(""))rootdir=pagecontext.getServletContext().getRealPath("/"); String rpath=rootdir+"/"+sPath; java.io.File f = new java.io.File(rpath); if(!f.exists())f.mkdirs(); rpath=f.getPath();</span>
总结:
在这个类中,我们发现写的真心的难看,但是,没有关系,我们只要会用了就可以了。