上转 下载 大家都做过 不过 Struts2提供了 更加方便的 方式 来实现上转 必须注意事项
commons-io-1.3.2.jar(http://jakarta.apache.org/commons/io/)
commons-fileupload-1.2.1.jar(http://commons.apache.org/fileupload/)
enctype属性指定的是表单数据的编码方式,该属性有如下3个值
废话也不说了 完成一个上转照片的例子 和QQ空间的上转照片的模式一样
页面端:
<!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> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>。。。。上转照片</title> <script language="javascript"> var count; function FoceFile(){ document.getElementById("showfile").innerHTML="选择你要上传的图片"; } function BlurFile(){ file = document.formAlbum.albumname.value; if(file == ""){ document.getElementById("showfile").innerHTML="<font color=\"red\">请选择你要上传的图片</font>"; } } function FoceCount(){ document.getElementById("showcount").innerHTML="你可以为你选择的图片添加备注"; } function BlurCount(){ count =document.formAlbum.count.value; if(count == ""){ document.getElementById("showcount").innerHTML="<font color=\"red\">备注为空,系统默认命名为未知</font>"; } } function sumbitAlbum(){ if(count == ""){ count = "未知"; } if(file ==""){ alert("请选择上传的图片"); return; } document.formAlbum.action="photo?parm=add&count="+count; document.formAlbum.submit(); } </script> </head> <body> <form id="form1" name="formAlbum" enctype="multipart/form-data" method="post" action=""> <div id="Layer3"> <table width="939" height="217" border="1" align="center" bordercolor="#FBFBD9"> <tr> <td width="212" height="51"><span class="STYLE2">上 转 照 片</span></td> <td width="98"> </td> <td width="235"> </td> <td width="299"> </td> <td width="61"> </td> </tr> <tr> <td height="20" colspan="5"><span class="STYLE5 STYLE3"><em>欢迎使用上传照片功能,在这里您可以把你喜爱的照片加入到你的相册,注意上转的图片不得大于3M</em></span> <strong>ENJOY!</strong></td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td><div align="right"><span class="STYLE1">上转照片:</span></div></td> <td> <label> <input name="albumname" type="file" id="albumname" onfocus="FoceFile()" onblur="BlurFile()"/> </label> </td> <td><div align="left" id="showfile"></div></td> <td> </td> </tr> <tr> <td> </td> <td><div align="right"><span class="STYLE1">照片备注:</span></div></td> <td><label> <input name="count" type="text" id="count" onfocus="FoceCount()" onblur="BlurCount()"/> </label></td> <td><div align="left" id="showcount"></div></td> <td> </td> </tr> <tr> <td height="17"> </td> <td> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> <td><label> <input type="button" name="Submit" value="创 建" onclick="sumbitAlbum()"/> <input type="reset" name="Submit2" value="重 置" /> </label></td> <td> </td> <td> </td> </tr> </table> </div> </form> </body> </html>
web.xml
<!-- 相片service --> <servlet> <servlet-name>photo</servlet-name> <servlet-class>com.album.service.PhotoServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>photo</servlet-name> <url-pattern>/photo</url-pattern> </servlet-mapping>
PhotoServlet(注意 上传时需要 一个临时目录 在这个我是手动创建的 在webroot 目录下 建名为 UploadImages 的空文件 )
package com.album.service; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.album.dao.imple.PhtotoDaoImple; import com.album.domain.PhotoInfo; import com.album.util.UploadImages; public class PhotoServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @SuppressWarnings("deprecation") @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("gbk"); resp.setCharacterEncoding("gbk"); resp.setContentType("text/html;charset=gbk"); PrintWriter out = resp.getWriter(); String parm = req.getParameter("parm"); if(parm.equals("show")){ //显示所有 相片 /............. }else if(parm.equals("add")){ //增加相片 //req.getRealPath("/")得到项目所在的根目录 String tempPath = req.getRealPath("/")+"UploadImages";//临时放图片的缓存区 String username =(String) req.getSession().getAttribute("userName"); // this.getServletContext().getRealPath("")得到servlet上下文的路径 -----》 项目所在的tomcat的目录 String uploadpath= this.getServletContext().getRealPath("")+"\\PhotoAlbum\\"+username+"\\photo";//图片存放的磁盘位置 UploadImages upload = new UploadImages(req,tempPath,uploadpath);// 调用UPloadImage类的方法 int falg=upload.uploadPhoto(); switch (falg) { case 1: out.println("<script language=\"javascript\">alert(\"图片文件超过3M,请重新选择\");window.location=\"gphoto.html\"</script>"); break; case 2: out.println("<script language=\"javascript\">alert(\"文件名为空,请重新选择\");window.location=\"gphoto.html\"</script>"); break; case 3: out.println("<script language=\"javascript\">alert(\"文件类型不匹配\");window.location=\"gphoto.html\"</script>"); break; case 4: //插入数据库 //得到文件名 /........... } }else if(parm.equals("del")){ //删除相册 /..... } }
UploadImage 类
package com.album.util; import java.io.File; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /******************************************************************************* * 本类是完成图片的上传功能 * <p> * 通过上转组件完成 * * @author 王亚磊 * */ public class UploadImages { private HttpServletRequest request;// 待处理的请求对象,从请求中分析出上转文件 private String tempPath;// 上转是产生的临时文件的路径 private String uploadPath;// 上传文件保存的路径 private String saveFileName = "";// 保存的文件名 private final String[] filetype = new String[] { "jpg", "jpeg", "gif", "bmp" };// 上转类型 public UploadImages(HttpServletRequest request, String tempPath, String uploadPath) { this.request = request; this.tempPath = tempPath; this.uploadPath = uploadPath; } @SuppressWarnings("unchecked") public int uploadPhoto() { int falg = 0; long filesize = 4 * 1024 * 1024;// 设置文件上传大小 为 4M // 磁盘文件列表工厂 DiskFileItemFactory dfif = new DiskFileItemFactory(); // 设置缓冲区大小 dfif.setSizeThreshold(4096); // 设置上转文件的临时路径 dfif.setRepository(new File(tempPath)); // 设置上传文件对象,用于设置上传文件属性及实现文件上传 ServletFileUpload sfu = new ServletFileUpload(dfif); sfu.setSizeMax(filesize);// 上传大小 List filelist = null; try { // 从请求中取出所有的表单域对象 返回的是一个List 也可以用泛型来做 List<FileItem> filelist = sfu.parseRequest(request); } catch (FileUploadException e) { // TODO Auto-generated catch block if (e instanceof SizeLimitExceededException) { falg = 1; return falg; } e.printStackTrace(); } // 遍历循环 取出 表单域中的值 Iterator fileitor = filelist.iterator(); while (fileitor.hasNext()) { FileItem fileitem = (FileItem) fileitor.next(); if (fileitem != null && !fileitem.isFormField()) { long size = 0L; size = fileitem.getSize(); String path = fileitem.getName(); if (size == 0 || path.equals("")) {// 判断上转路径 及其大小 falg = 2; break; } else { boolean flagtype = this.checkFileType(path);// 检测文件的扩展名 if (flagtype == false) { falg = 3; break; } else { try { File userAlbumPath = new File(uploadPath); if (!userAlbumPath.isDirectory() && !userAlbumPath.isFile()) { userAlbumPath.mkdirs(); } fileitem.write(new File(userAlbumPath, saveFileName)); falg = 4; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } return falg; } // 判断文件上传类型 并用随即生成 文件名 防止 文件名相同而被代替 private boolean checkFileType(String filename) { // TODO Auto-generated method stub boolean typeflag = false; String fullname = filename.substring(filename.lastIndexOf("\\") + 1); String typename = fullname.substring(fullname.lastIndexOf(".") + 1); int allowedExtCount = filetype.length; for (int i = 0; i < allowedExtCount; i++) { if (filetype[i].equals(typename)) { long now = System.currentTimeMillis(); String prefix = String.valueOf(now); saveFileName = prefix + "." + typename; typeflag = true; break; } } return typeflag; } public String getSaveFileName() { return this.saveFileName; } }
以上就是 普通的上转是不是 很繁琐 虽然不难 但很麻烦 ,Struts2提供的上转机制虽然也是建立在这个上转组件之上的
但他又对此进行了包装 使用很方便 下面 还是这个例子 我们用Struts2来完成
第一步 指定 上转文件的解析器 Struts2提供了三种解析器(默认的就是 commons-fileupload)
# struts.multipart.parser=cos # struts.multipart.parser=pell struts.multipart.parser=jakarta