前一篇文章可以看到对jquery uploadify的属性的讲解,这里给出具体的java代码实现,代码基于servlet,实现了上传图片并预览的效果,不多说,上代码
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>Insert title here
其中,js中定义了上传处理的uploadifyServlet地址,所以下一步就是编写改servlet了
uploadifyServlet.java
public class uploadifyServlet extends HttpServlet { private String configPath="d:/p_w_picpath/"; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String ret_fileName = null;//返回给前端已修改的图片名称 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); // 文件保存目录路径 String savePath = configPath; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); try { List items = upload.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { DiskFileItem item = (DiskFileItem) itr.next(); String fileName = item.getName(); if(fileName!=null){ ret_fileName = fileName; } if (!item.isFormField()) { try { File uploadedFile = new File(savePath,fileName); OutputStream os = new FileOutputStream(uploadedFile); InputStream is = item.getInputStream(); byte buf[] = new byte[1024];// 可以修改 1024 以提高读取速度 int length = 0; while ((length = is.read(buf)) > 0) { os.write(buf, 0, length); } // 关闭流 os.flush(); os.close(); is.close(); } catch (Exception e) { e.printStackTrace(); } } } } catch (FileUploadException e) { e.printStackTrace(); } //将已修改的图片名称返回前端 out.print(ret_fileName); out.flush(); out.close(); }}
上述代码的意思很简单,将上传的文件放入指定的文件夹,并返回图片的名称。
到此为止,上传就结束了,下面是预览。
在onUploadSuccess中,我们得到了上传成功图片的返回的图片名称,其中我们定义了实现预览效果的后台servlet,getImgServlet
下面给出改servlet的代码
public class getImg extends HttpServlet { private String configPath="d:/p_w_picpath/"; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String file = request.getParameter("file"); File pic = new File(configPath+file); FileInputStream fis = new FileInputStream(pic); OutputStream os = response.getOutputStream(); try { int count = 0; byte[] buffer = new byte[1024 * 1024]; while ((count = fis.read(buffer)) != -1) os.write(buffer, 0, count); os.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (os != null) os.close(); if (fis != null) fis.close(); } }}
上述代码很简单,得到传过来的文件名之后,直接发送文件流过去,实现图片显示
具体的项目包地址如下,大家可直接下载运行:
http://yun.baidu.com/share/link?shareid=702477080&uk=2836507213