uploadify.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> <!--装载文件--> <link href="/res/js/widget/jquery/uploadify.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="/res/js/widget/jquery/jquery.min.js"></script> <script type="text/javascript" src="/res/js/widget/jquery/swfobject.js"></script> <script type="text/javascript" src = "/res/js/widget/jquery/jquery.uploadify.v2.1.0.js"></script> <!--ready事件--> <script type="text/javascript"> $(document).ready(function() { $("#${param['componentID']}").uploadify({ 'uploader': '/res/js/widget/jquery/uploadify.swf', 'script': '/servlet/uploadify?markWater=${param.markWater}', //'script': '/imageUploadService.htm?markWater=${param.markWater}', 'cancelImg': '/res/js/widget/jquery/cancel.png', 'queueID' : '${param['componentID']}_queue', //和存放队列的DIV的id一致 //'fileDataName': 'fileupload', //必须,和以下input的name属性一致 'auto' : false, //是否自动开始 'multi': true, //是否支持多文件上传 'buttonText': 'OPEN', //按钮上的文字 'simUploadLimit' : 1, //一次同步上传的文件数目 'sizeLimit': 19871202, //设置单个文件大小限制,单位为byte 'queueSizeLimit' : ${not empty param['maxPhotos'] ? param['maxPhotos'] : '10'}, //队列中同时存在的文件个数限制 'fileDesc': '支持格式:jpg/gif/jpeg/png/bmp.', //如果配置了以下的'fileExt'属性,那么这个属性是必须的 'fileExt': '*.jpg;*.gif;*.jpeg;*.png;*.bmp',//允许的格式 'onComplete': function (event, queueID, fileObj, response, data) { <c:choose> <c:when test="${param['preview'] eq 'true'}"> var putin = "<div class='backimge' id='"+queueID+"'><div class='backtop'></div><div class='backcenter'><div class='bimage'><img src='${Constants_IMAGE_URL}"+response+"' width='137' height='103'></div><div class='btxtd'>"; <c:if test="${param['photoTitleEnabled'] eq 'true'}"> putin += "<input type='text' name=${param['storeField']}Title id=${param['componentID']}Title size='20' />"; </c:if> putin +="</div><div style='text-align:center'><input type='button' id='publish' onclick=javascript:delPhoto('"+queueID+"'); name='publish' class='post_bt' value=' 删除 '></div></div><div class='backbottom'></div><input type='hidden' value='"+response+"' name='${param['storeField']}'></div>"; $('#${param['componentID']}_show').append(putin); </c:when> <c:otherwise> $('#${param['componentID']}_show').append("<input type='hidden' value='"+response+"' name='${param['storeField']}'>"); //alert("文件:" + fileObj.name + "上传成功");<img src='${Constants_IMAGE_URL}"+response+"' width='100' height='150'> </c:otherwise> </c:choose> }, 'onError': function(event, queueID, fileObj) { alert("文件:" + fileObj.name + "上传失败"); }, 'onCancel': function(event, queueID, fileObj){ } }); }); function delPhoto(id){ $('div').remove('#'+id); } </script> <!-- 上传队列 DIV --> <div id="${param['componentID']}_queue"></div> <p><input type="file" name="uploadify" id="${param['componentID']}" value="upload" /></p> <p> <a href="javascript:jQuery('#${param['componentID']}').uploadifyUpload()">开始上传</a> <a href="javascript:jQuery('#${param['componentID']}').uploadifyClearQueue()">取消所有上传</a> </p> <div id="${param['componentID']}_show" class="messageback"> <!-- 根据传过来指定格式的字符串,来填充预览图片列表 --> <c:if test="${not empty param['photoLinks']}"> <c:forEach items="${fn:split(param['photoLinks'], ',')}" var="phohoLink" varStatus="s"> <c:choose> <c:when test="${param['preview'] eq 'true'}"> <div class="backimge" id="${param['componentID']}_image_${s.count}"> <div class="backtop"></div> <div class="backcenter"> <div class="bimage"><img src="${Constants_IMAGE_URL}${phohoLink}" width="137" height="103"></div> <div class="btxtd"> <c:if test="${param['photoTitleEnabled'] eq 'true'}"> <input type="text" name="${param['storeField']}Title" id="${param['storeField']}Title" size="20" /> </c:if> </div> <div style="text-align:center"> <input id="publish" onclick="javascript:delPhoto('${param['componentID']}_image_${s.count}');" name="publish" class="post_bt" onmouseover="this.className='post_bt2';" onmouseout="this.className='post_bt';" value=" 删除 " type="button"> </div> </div> <div class="backbottom"></div> <input type="hidden" value="${phohoLink}" name='${param['storeField']}'> </div> </c:when> <c:otherwise> <input type="hidden" value="${phohoLink}" name='${param['storeField']}'> </c:otherwise> </c:choose> </c:forEach> </c:if> </div> <!-- 参数说明 ${param['storeField']} 后台处理的name ${param['preview']} 是否预览 ${param['photoTitleEnabled']} 是否显示图片tilte填入框 ${param['maxPhotos']} 最大上传文件个数 ${param['photoLinks']} 修改图片时用来填充预览图片用的 ${param['componentID']} 唯一的ID -->
使用案例片段
<c:import url="../components/uploadify.jsp"> <c:param name="componentID" value="testComponent1" /> <c:param name="storeField" value="photos" /> <c:param name="preview" value="true" /> <c:param name="photoTitleEnabled" value="false" /> <c:param name="maxPhotos" value="2" /> </c:import>
package com.sikoo.web.utils; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import com.sikoo.utils.App; import com.sikoo.utils.FileRepository; public class UploadifyServlet extends HttpServlet { /** * Servlet初始化方法 */ public void init() throws ServletException { } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("--- BEGIN---"); boolean mark = false; String markWater= request.getParameter("markWater"); if(markWater.equals("true")){ mark = true; } DiskFileItemFactory fac = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(fac); upload.setHeaderEncoding("utf-8"); List fileList = null; try { fileList = upload.parseRequest(request); } catch (FileUploadException ex) { return; } Iterator<FileItem> it = fileList.iterator(); String name = ""; String extName = ""; while (it.hasNext()) { FileItem item = it.next(); if (!item.isFormField()) { name = item.getName(); long size = item.getSize(); String type = item.getContentType(); System.out.println(size + " " + type); if (name == null || name.trim().equals("")) { continue; } // 扩展名格式: if (name.lastIndexOf(".") >= 0) { extName = name.substring(name.lastIndexOf(".")); } try { // item.write(saveFile); //下面为保存到指定的目录,并返回保存的目录 FileRepository fileRepository=(FileRepository)App.getBean("fileRepository"); InputStream in = item.getInputStream(); String repo = fileRepository.savePhotoFile("/tmp", in, extName,mark); System.out.println(repo+"...........repo"); response.getWriter().write(repo);//对应回调函数中response的值 } catch (Exception e) { e.printStackTrace(); } } } System.out.println("--- END---"); } }
大家可以根据自己的页面样式做调整