dwz+jquery+fileupload+springmvc實現文件上傳及圖片預覽

1 前臺jsp:文件的上傳利用瞭iframe實現局部刷新功能。使用瞭apache的fileupload組件,用到的jar: commons-fileupload.jar,commons-io.jar
DiskFileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setHeaderEncoding("utf-8");

 

 

Html代碼 
   <%@ page contentType="text/html;charset=UTF-8" %> 
<%@page import="com.pdcss.bmxxfb.model.*" %> 
<%@ include file="/commons/taglibs.jsp" %> 
<style> 
.perview {width:200px;background:#fff;font-size:12px; border-collapse:collapse;} 
.perview td, .perview th {padding:0px;border:0px;} 
.perview th {background-color:#f0f0f0; height:20px;} 
.perview a:link, .perview a:visited, .perview a:hover, .perview a:active {color:#00F;} 
.perview table{ width:100%;border:1px solid #ccc;border-collapse:collapse;} 
</style> 
<script type="text/javascript" src="${ctx}/scripts/imgPreview/CJL.0.1.min.js"></script> 
<script type="text/javascript" src="${ctx}/scripts/imgPreview/QuickUpload.js"></script> 
<script type="text/javascript" src="${ctx}/scripts/imgPreview/ImagePreviewd.js"></script> 
<script type="text/javascript"> 
<!– 
    //處理文件上傳後的回調,如果成功,則關閉當前窗口,刷新index 
    function callback(flag,msg){ 
        if(flag=='true'){ 
            $("#pdtpNewForm").parent().parent().hide(); 
            navTab.reload('/bmxxfb/wzxxfbpdtp/manager'); 
        }else{ 
            alert(msg); 
        } 
    } 
    //提交之前檢查各字段 
    function checkPdtpSubmit(){ 
        var zzdm = $("#pdtpNewForm #zzdm"); 
        if(zzdm.val().trim() ==""){ 
            alert("組織代碼不能為空!");  
            zzdm.focus(); 
            return false; 
        } 
        var bmdm = $("#pdtpNewForm #bmdm"); 
        if(bmdm.val().trim() ==""){ 
            alert("組織代碼不能為空!");  
            bmdm.focus(); 
            return false; 
        } 
        var tpbt = $("#pdtpNewForm #tpbt"); 
        if(tpbt.val().trim() ==""){ 
            alert("飄動主題不能為空!");  
            tpbt.focus(); 
            return false; 
        } 
        var tplj = $("#pdtpNewForm #tplj"); 
        if(tplj.val().trim() ==""){ 
            alert("鏈接地址不能為空!");  
            tplj.focus(); 
            return false; 
        } 
        var imgFile = $("#pdtpNewForm #imgFile"); 
        if(imgFile.val().trim() ==""){ 
            alert("圖片不能為空");  
            imgFile.focus(); 
            return false; 
        } 
        var extStart=imgFile.val().lastIndexOf(".");  
        var ext=imgFile.val().substring(extStart,imgFile.val().length).toLowerCase();  
        if(ext!=".bmp"&&ext!=".png"&&ext!=".gif"&&ext!=".jpg"&&ext!=".jpeg"){  
            alert("圖片限於bmp,png,gif,jpeg,jpg格式"); 
            imgFile.focus();  
            return false;  
        }  
        var regl=/^\+?[1-9][0-9]*$/; 
        var kd = $("#pdtpNewForm #kd"); 
        if(!regl.test(kd.val())){ 
            alert("寬度應該為正整數!"); 
            kd.focus(); 
            return false; 
        } 
        if(parseInt(kd.val())>225){ 
            alert("寬度不能超過225!"); 
            kd.focus(); 
            return false; 
        } 
        var gd = $("#pdtpNewForm #gd"); 
        if(!regl.test(gd.val())){ 
            alert("寬度應該為正整數!"); 
            gd.focus(); 
            return false; 
        } 
        if(parseInt(gd.val())>200){ 
            alert("高度不能超過200!"); 
            gd.focus(); 
            return false; 
        } 
        return true; 
    } 
    function changeValue(flag){ 
        if(flag=='kd'){ 
            $("#pdtpNewForm #kd").val($("#kd_tem").val()); 
        } 
        if(flag == 'gd'){ 
            $("#pdtpNewForm #gd").val($("#gd_tem").val()); 
        } 
    } 
    var ip = new ImagePreview( $$("imgFile"), $$("idImg"),{ 
    maxWidth: 225, maxHeight: 170, action: "viewImg.jsp" 
    }); 
    ip.img.src = ImagePreview.TRANSPARENT; 
    ip.file.onchange = function(){ 
        var imgFile = $("#pdtpNewForm #imgFile"); 
        if(imgFile.val().trim() ==""){ 
            alert("圖片不能為空");  
            imgFile.focus(); 
            return false; 
        } 
        var extStart=imgFile.val().lastIndexOf(".");  
        var ext=imgFile.val().substring(extStart,imgFile.val().length).toLowerCase();  
        if(ext!=".bmp"&&ext!=".png"&&ext!=".gif"&&ext!=".jpg"&&ext!=".jpeg"){  
            alert("圖片限於bmp,png,gif,jpeg,jpg格式"); 
            imgFile.focus();  
            return false;  
        }  
        ip.preview();  
        $("#idImg").attr("src","data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="); 
    }; 
    $(document).ready(function(){ 
        $("#idImg").attr("src","data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="); 
    }); 
//–> 
</script> 
 
    <form:form method="post" action="${ctx}/wzxxfbpdtp/save" target="hidden_frame" id="pdtpNewForm" enctype="multipart/form-data" modelAttribute="wzXxfbPdtp"> 
        <p class="pageContent" layoutH="30"> 
        <p class="pageFormContent" align="center" style="overflow: hidden;"> 
            <input type="hidden" id="pkid" name="pkid" value="${wzXxfbPdtp.pkid}"/> 
            <input type="hidden" name="imgPath" id="imgPath" /> 
            <input type="hidden" name="testH" value="testH"> 
            <table align="center" width="500px" height="300px" border="0" cellpadding="0" cellspacing="0" style="margin-top: 10px;text-align: center;border-spacing: 10px;"> 
                <tr> 
                    <td align="right" width="70px"> 
                        <%=WzXxfbPdtp.ALIAS_ZZDM%>: 
                    </td> 
                    <td width="120px"> 
                        <form:input path="zzdm" id="zzdm" size="25" readonly="true" value="${zzdm }" maxlength="50" /> 
                    </td> 
                    <td width="225px" rowspan="6"> 
                        <table border="0"  cellpadding="0" cellspacing="0"> 
                            <tr><th bgcolor="#f0f0f0" style="line-height: 25px;"><center>預覽圖</center></th></tr> 
                            <tr> 
                                <td> 
                                    <p style="width: 225px;height: 170px;border:1px solid #99BBE8"> 
                                        <table border="0" class="perview"> 
                                            <tr> 
                                                <td align="center"><img id="idImg"/></td> 
                                            </tr> 
                                        </table> 
                                    </p> 
                                </td> 
                            </tr> 
                        </table> 
                    </td> 
                </tr> 
                <tr> 
                    <td width="70px"> 
                        <label for="bmdm"><%=WzXxfbPdtp.ALIAS_BMDM%>:</label> 
                    </td> 
                    <td width="120px"> 
                        <form:input path="bmdm" id="bmdm" size="25" readonly="true" value="${bmdm }" maxlength="50" /> 
                    </td> 
                </tr> 
                <tr> 
                    <td width="70px"> 
                        <label for="tpbt"><%=WzXxfbPdtp.ALIAS_TPBT%>:</label> 
                    </td> 
                    <td width="120px"> 
                        <form:input path="tpbt" id="tpbt" size="25"  cssClass="required" maxlength="100" /> 
                    </td> 
                </tr> 
                <tr> 
                    <td width="70px"> 
                        <label for="tplj"><%=WzXxfbPdtp.ALIAS_TPLJ%>:</label> 
                    </td> 
                    <td width="120px"> 
                        <form:input path="tplj" id="tplj" size="25"  cssClass="required" maxlength="1000" /> 
                    </td> 
                </tr> 
                <tr> 
                    <td width="70px"> 
                        圖片寬高: 
                    </td> 
                    <td width="120px"> 
                        <table> 
                            <tr> 
                                <td> 
                                    <input id="kd_tem" name="kd_tem" value="160" onchange="javascript:changeValue('kd');" size="8" maxlength="4"> 
                                    <input type="hidden" id="kd" name="kd" value="160"> 
                                </td> 
                                <td>&nbsp;&nbsp;單位(px)</td> 
                            </tr> 
                        </table> 
                    </td> 
                </tr> 
                <tr> 
                    <td width="70px"> 
                        <label for="gd"><%=WzXxfbPdtp.ALIAS_GD%>:</label> 
                    </td> 
                    <td width="120px"> 
                        <table> 
                            <tr> 
                                <td> 
                                    <input id="gd_tem" name="gd_tem" value="100" size="8" maxlength="4" onchange="javascript:changeValue('gd');"> 
                                    <input type="hidden" id="gd" name="gd" value="100"> 
                                </td> 
                                <td>&nbsp;&nbsp;單位(px)</td> 
                            </tr> 
                        </table> 
                    </td> 
                </tr> 
                <tr> 
                    <td colspan="2" width="190px"> 
                        <label for="sfpd"><%=WzXxfbPdtp.ALIAS_SFPD%>:</label> 
                        <label><input type="radio"  name="sfpd" value="1" checked="checked">飄動</label> 
                        <label><input type="radio"  name="sfpd" value="0">不飄動</label> 
                    </td> 
                    <td><font color="red">隻允許上傳1M內jpg,jpeg,gif,png格式圖片</font></td> 
                </tr> 
                <tr> 
                    <td width="70px">選擇圖片</td> 
                    <td colspan="2"><input id="imgFile" name="imgFile" type="file" /></td> 
                </tr> 
            </table> 
        </p> 
        </p> 
        <iframe name="hidden_frame" id="hidden_frame" src="message.html" style="display:none"></iframe> 
        <p class="formBar"> 
            <ul> 
                <li> 
                    <p class="buttonActive"><p class="buttonContent"><button type="submit"  onclick="return checkPdtpSubmit();">保存</button></p></p> 
                </li> 
                <li> 
                    <p class="button"><p class="buttonContent"><button type="button" class="close">關閉</button></p></p> 
                </li> 
            </ul> 
        </p> 
    </form:form> 


2 後臺Controller
Java代碼 
import java.io.File; 
import java.io.PrintWriter; 
import java.io.UnsupportedEncodingException; 
import java.text.DateFormat; 
import java.text.SimpleDateFormat; 
import java.util.ArrayList; 
import java.util.Calendar; 
import java.util.Date; 
import java.util.Iterator; 
import java.util.List; 
 
import javacommon.base.BaseRestSpringController; 
 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import javax.validation.Valid; 
 
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 org.springframework.beans.propertyeditors.CustomDateEditor; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.ModelMap; 
import org.springframework.validation.BindingResult; 
import org.springframework.web.bind.WebDataBinder; 
import org.springframework.web.bind.annotation.InitBinder; 
import org.springframework.web.bind.annotation.ModelAttribute; 
import org.springframework.web.bind.annotation.PathVariable; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RequestParam; 
 
import cn.org.rapid_framework.page.Page; 
import cn.org.rapid_framework.web.scope.Flash; 
 
import com.common.consts.StaticDict; 
 
 
 
/**
 * @author pdcss
 * 這裡是控制層,用於編寫頁面跳轉控制,容器變量管理,JavaBean收集傳遞的代碼
 * 嚴禁出現 SQL,HQL,HTML,JS,CSS代碼
 * 可以將其他service層註入這裡,但嚴禁將dao層註入這裡
 
 *
 */ 
@Controller 
@RequestMapping("/wzxxfbpdtp") 
public class WzXxfbPdtpController extends BaseRestSpringController<WzXxfbPdtp,java.lang.String>{ 
    //默認多列排序,example: username desc,createTime asc 
    protected static final String DEFAULT_SORT_COLUMNS = "";  
    private WzXxfbPdtpManager wzXxfbPdtpManager; 
    private final String LIST_ACTION = "redirect:/wzxxfbpdtp/manager"; 
     
    /** 
     * 增加setXXXX()方法,spring就可以通過autowire自動設置對象屬性,註意大小寫
 
     **/ 
    public void setWzXxfbPdtpManager(WzXxfbPdtpManager manager) { 
        this.wzXxfbPdtpManager = manager; 
    } 
     
    /** binder用於bean屬性的設置 */ 
    @InitBinder   
    public void initBinder(WebDataBinder binder) {   
            binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));   
    } 
        
    /**
     * 增加瞭@ModelAttribute的方法可以在本controller方法調用前執行,可以存放一些共享變量,如枚舉值,或是一些初始化操作
     */ 
    @ModelAttribute 
    public void init(ModelMap model) { 
        model.put("now", new java.sql.Timestamp(System.currentTimeMillis())); 
        /**
         * 讀入靜態字典
         */ 
        StaticDict.fillMapAll(model); 
    } 
    /**
     * 初始化新增,修改,查詢列表頁面數據
     * @param model
     */ 
    public void initAddAndUpdate(ModelMap model) { 
    }    
 
 
    /** 保存新增,@Valid標註spirng在綁定對象時自動為我們驗證對象屬性並存放errors在BindingResult  */ 
    @SuppressWarnings("unchecked") 
    @RequestMapping(value = "/save") 
    public String create(ModelMap model,@Valid WzXxfbPdtp wzXxfbPdtp,HttpServletRequest request,HttpServletResponse response)throws Exception  { 
        DiskFileItemFactory fac = new DiskFileItemFactory(); 
        ServletFileUpload upload = new ServletFileUpload(fac); 
        upload.setHeaderEncoding("utf-8"); 
        List fileList=null; 
        try { 
            fileList = upload.parseRequest(request); 
        } catch (FileUploadException e1) { 
            e1.printStackTrace(); 
        } 
        //根路徑 
        String root=request.getSession().getServletContext().getRealPath(""); 
        //圖片保存完整路徑 
        String savePath = root+File.separator+"pdtpFolder"+File.separator; 
        File f1 = new File(savePath); 
        if (!f1.exists()) { 
            f1.mkdirs(); 
        } 
        //圖片名稱 
        String name = ""; 
        //新生成的圖片名稱 
        String newName = ""; 
        //擴展名 
        String extName = ""; 
        String message = ""; 
        boolean flag = true; 
        Iterator<FileItem> it = fileList.iterator(); 
        while (it.hasNext()) { 
            FileItem item = it.next(); 
            //給取表單域的值,賦給wzXxfbPdtp對象 
            setFormFields(wzXxfbPdtp, item); 
            // 如果是文件類型字段 
            if (!item.isFormField()) { 
                name = item.getName(); 
                long size = item.getSize(); 
                if(size>(1024*1024)){ 
                    message="文件"+item.getName()+"大超過瞭1M,上傳失敗!"; 
                    break; 
                } 
                // 擴展名格式: 
                if (name.lastIndexOf(".") >= 0) { 
                    extName = name.substring(name.lastIndexOf(".")); 
                } 
                // 定義允許上傳的文件類型 
                List<String> fileTypes = new ArrayList<String>(); 
                fileTypes.add(".jpg"); 
                fileTypes.add(".jpeg"); 
                fileTypes.add(".gif"); 
                fileTypes.add(".png"); 
                if(!fileTypes.contains(extName.toLowerCase())){ 
                    message = "隻允許上傳jpg,jpeg,gif,png格式的圖片"; 
                    flag = false; 
                } 
                if(flag) { 
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ssSSS"); 
                    Calendar calendar = Calendar.getInstance(); 
                    //以當前時間為文件名 格式如:2011-09-03-19-30-36047  
                    newName = df.format(calendar.getTime()); 
                    //name = UUID.randomUUID().toString(); 
                    File newFile = new File(savePath + newName + extName); 
                    item.write(newFile); 
                    message="上傳文件"+item.getName()+"成功"; 
                    model.addAttribute("successFileName",newName + extName); 
                    //設置圖片的相對地址 
                    wzXxfbPdtp.setTpdz("pdtpFolder/"+newName+extName); 
                    //圖片原名稱 
                    wzXxfbPdtp.setTpmc(name); 
                }  
            } 
        } 
        wzXxfbPdtpManager.save(wzXxfbPdtp); 
//      dwzCallback(model,CREATED_SUCCESS); 
        response.setContentType("text/html"); 
        response.setCharacterEncoding("utf-8"); 
        PrintWriter out = response.getWriter(); 
        out.write("<script>parent.callback('"+flag+"','"+message+"')</script>"); 
//      return LIST_ACTION; 
        return null; 
    } 
     
     
    /** 保存更新,@Valid標註spirng在綁定對象時自動為我們驗證對象屬性並存放errors在BindingResult  */ 
    @SuppressWarnings("unchecked") 
    @RequestMapping(value="/{id}/update",method=RequestMethod.POST) 
    public String update(ModelMap model,@PathVariable java.lang.String id,@Valid WzXxfbPdtp wzXxfbPdtp,BindingResult errors,HttpServletRequest request,HttpServletResponse response) throws Exception { 
        DiskFileItemFactory fac = new DiskFileItemFactory(); 
        ServletFileUpload upload = new ServletFileUpload(fac); 
        upload.setHeaderEncoding("utf-8"); 
        List fileList=null; 
        try { 
            fileList = upload.parseRequest(request); 
        } catch (FileUploadException e1) { 
            e1.printStackTrace(); 
        } 
        String root=request.getSession().getServletContext().getRealPath(""); 
        String savePath = root+File.separator+"pdtpFolder"+File.separator; 
        File f1 = new File(savePath); 
        if (!f1.exists()) { 
            f1.mkdirs(); 
        } 
        String name = ""; 
        String newName = ""; 
        String extName = ""; 
        String message = ""; 
        //修改之前 圖片地址 
        String oldFilePath = ""; 
        boolean flag = true; 
        wzXxfbPdtp.setPkid(id); 
        Iterator<FileItem> it = fileList.iterator(); 
        while (it.hasNext()) { 
            FileItem item = it.next(); 
            setFormFields(wzXxfbPdtp, item); 
            if(item.isFormField()){ 
                String field = item.getFieldName(); 
                if(field.equals("oldFilePath")){ 
                    oldFilePath = item.getString("utf-8"); 
                    wzXxfbPdtp.setTpdz(oldFilePath); 
                } 
                if(field.equals("tpmc")){ 
                    wzXxfbPdtp.setTpmc(item.getString("utf-8")); 
                } 
            } 
            if (!item.isFormField()) { 
                name = item.getName(); 
                if(name != null && !"".equals(name)){ 
                    long size = item.getSize(); 
                    if(size>(1024*1024)){ 
                        message="文件"+item.getName()+"大超過瞭1M,上傳失敗!"; 
                        break; 
                    } 
                    // 擴展名格式: 
                    if (name.lastIndexOf(".") >= 0) { 
                        extName = name.substring(name.lastIndexOf(".")); 
                    } 
                    // 定義允許上傳的文件類型 
                    List<String> fileTypes = new ArrayList<String>(); 
                    fileTypes.add(".jpg"); 
                    fileTypes.add(".jpeg"); 
                    fileTypes.add(".gif"); 
                    fileTypes.add(".png"); 
                    if(!fileTypes.contains(extName.toLowerCase())){ 
                        message = "隻允許上傳jpg,jpeg,gif,png格式的圖片"; 
                        flag = false; 
                    } 
                    if(flag) { 
                        DateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ssSSS"); 
                        Calendar calendar = Calendar.getInstance(); 
                        //以當前時間為文件名 格式如:2011-09-03-19-30-36047  
                        newName = df.format(calendar.getTime()); 
                        //name = UUID.randomUUID().toString(); 
                        File newFile = new File(savePath + newName + extName); 
                        item.write(newFile); 
                        message="上傳文件"+item.getName()+"成功"; 
                        model.addAttribute("successFileName",newName + extName); 
                        //設置圖片的相對地址 
                        wzXxfbPdtp.setTpdz("pdtpFolder/"+newName+extName); 
                        //圖片原名稱 
                        wzXxfbPdtp.setTpmc(name); 
                    }  
                } 
            } 
        } 
        wzXxfbPdtpManager.update(wzXxfbPdtp); 
        if(name != null && !"".equals(name) && flag == true){ 
            File oldImg = new File(root+File.separator+oldFilePath); 
            if(oldImg.exists()){ 
                oldImg.delete(); 
            } 
        } 
    //  dwzCallback(model,UPDATE_SUCCESS); 
        response.setContentType("text/html"); 
        response.setCharacterEncoding("utf-8"); 
        PrintWriter out = response.getWriter(); 
        out.write("<script>parent.callbackEdit('"+flag+"','"+message+"')</script>"); 
    //  return LIST_ACTION; 
        return null; 
    } 
    /*
     * 因為前臺Form表單的 enctype="multipart/form-data",不能再通過request.getParameter()來取得參數,隻能通過以下的方法:取得Form表單各文本域的值,賦給wzXxfbPdtp對象
     */ 
    private void setFormFields(WzXxfbPdtp wzXxfbPdtp, FileItem item) throws UnsupportedEncodingException { 
        if(item.isFormField()){ 
            String field = item.getFieldName(); 
            if(field.equals("zzdm")){ 
                String zzdm = item.getString("utf-8"); 
                wzXxfbPdtp.setZzdm(zzdm); 
            } 
            if(field.equals("bmdm")){ 
                String bmdm = item.getString("utf-8"); 
                wzXxfbPdtp.setBmdm(bmdm); 
            } 
            if(field.equals("tpbt")){ 
                String tpbt = item.getString("utf-8"); 
                wzXxfbPdtp.setTpbt(tpbt); 
            } 
            if(field.equals("tplj")){ 
                String tplj = item.getString("utf-8"); 
                wzXxfbPdtp.setTplj(tplj); 
            } 
            if(field.equals("kd")){ 
                String kd = item.getString("utf-8"); 
                wzXxfbPdtp.setKd(Integer.parseInt(kd)); 
            } 
            if(field.equals("gd")){ 
                String gd = item.getString("utf-8"); 
                wzXxfbPdtp.setGd(Integer.parseInt(gd)); 
            } 
            if(field.equals("sfpd")){ 
                String sfpd = item.getString("utf-8"); 
                wzXxfbPdtp.setSfpd(sfpd); 
            } 
        } 
    } 
     
    /** 刪除 */ 
    @RequestMapping(value = "/{id}/delete") 
    public String delete(ModelMap model,@PathVariable java.lang.String id,HttpServletRequest request) { 
        WzXxfbPdtp pdtp = wzXxfbPdtpManager.getById(id); 
        String path = pdtp.getTpdz(); 
        //得到圖片存放的完整路徑 
        String folder =  path.substring(0, path.lastIndexOf("/")); 
        //得到圖片的名稱 
        String name =  path.substring(path.lastIndexOf("/")+1); 
        //得到圖片存放的完整路徑 
        String savePath = request.getSession().getServletContext().getRealPath("")+File.separator+folder+File.separator+name; 
        wzXxfbPdtpManager.removeById(id); 
        File f1 = new File(savePath); 
        if(f1.exists()){ 
            f1.delete(); 
        } 
        dwzCallback(model,DELETE_SUCCESS); 
        return LIST_ACTION; 
    } 
 
    /** 批量刪除 */ 
    @RequestMapping(value = "/batchDeletes") 
    public String batchDelete(ModelMap model,@RequestParam("items") String items,HttpServletRequest request) { 
        String[] arr_items = items.split(","); 
        WzXxfbPdtp pdtp = null; 
        for(int i = 0; i < arr_items.length; i++) { 
            pdtp = wzXxfbPdtpManager.getById(arr_items[i]); 
            wzXxfbPdtpManager.removeById(arr_items[i]); 
            String path = pdtp.getTpdz(); 
            //得到圖片存放的完整路徑 
            String folder =  path.substring(0, path.lastIndexOf("/")); 
            //得到圖片的名稱 
            String name =  path.substring(path.lastIndexOf("/")+1); 
            //得到圖片存放的完整路徑 
            String savePath = request.getSession().getServletContext().getRealPath("")+File.separator+folder+File.separator+name; 
            File f1 = new File(savePath); 
            if(f1.exists()){ 
                f1.delete(); 
            } 
        } 
        dwzCallback(model,DELETE_SUCCESS); 
        return LIST_ACTION; 
    } 
    /**
     * DWZ 回調函數,封裝瞭操作的結果
     * 
     * @param status
     */ 
    public void dwzCallback(ModelMap model,String status){ 
        if(CREATED_SUCCESS.equals(status) || UPDATE_SUCCESS.equals(status) || DELETE_SUCCESS.equals(status) ){ 
            Flash.current().success(status); //存放在Flash中的數據,在下一次http請求中仍然可以讀取數據,error()用於顯示錯誤消息 
            /**
             * statusCode 200:成功 300:失敗 301:
             */ 
            model.addAttribute("statusCode", "200"); 
            /**
             * 返回後需要刷新的 tab 的ID ,如不填寫則不刷新
             */ 
            model.addAttribute("navTabId", "BM01040000"); 
            /**
             * 返回後需要調用的 js 方法, closeCurrent: 關閉當前tab頁(一般用於在tab頁打開的新增,編輯頁面)
             */ 
            if(! DELETE_SUCCESS.equals(status)){ 
                model.addAttribute("callbackType", "closeCurrent"); 
            } 
            /**
             * 返回後提示欄顯示的信息
 
             */ 
            model.addAttribute("message", status); 
        } 
    } 


圖片預覽需要用到的js:
CJL.0.1.min.js
ImagePreviewd.js
QuickUpload.js

3下面是實現圖片預覽的servlet


Java代碼 
package com.common.controller; 
 
import java.awt.Color; 
import java.awt.Graphics2D; 
import java.awt.Image; 
import java.awt.geom.AffineTransform; 
import java.awt.image.AffineTransformOp; 
import java.awt.image.BufferedImage; 
import java.io.ByteArrayOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.util.Iterator; 
import java.util.List; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServletRequest; 
import sun.misc.BASE64Encoder; 
import javax.imageio.*; 
 
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 org.apache.commons.io.output.DeferredFileOutputStream; 
import org.apache.log4j.Logger; 
 
import com.sun.image.codec.jpeg.JPEGCodec; 
import com.sun.image.codec.jpeg.JPEGImageEncoder; 
 
 
public class ImagePreview { 
    private final static Logger LOGGER = Logger.getLogger(ImagePreview.class); 
    public ImagePreview(){ 
         
    } 
     
    public String ProcessRequest(HttpServletRequest request) throws ServletException, IOException{ 
        BASE64Encoder encoder = new BASE64Encoder(); 
         
        byte[] bs = null; 
        long filesize = 0; 
         
        DiskFileItemFactory factory = new DiskFileItemFactory(); 
         
        int width = 0; 
        int height = 0; 
         
        InputStream inputStream = null; 
        ByteArrayOutputStream op = null; 
        DeferredFileOutputStream dfo = null; 
         
        try{ 
            factory.setSizeThreshold(4096);// 設置緩沖,這個值決定瞭是fileinputstream還是bytearrayinputstream 
            //factory.setRepository(new File("d:\\temp"));//設置臨時存放目錄,默認是new File(System.getProperty("java.io.tmpdir")) 
            ServletFileUpload sfileUpLoad = new ServletFileUpload(factory); 
            sfileUpLoad.setSizeMax(1*1024*1024);//1M 
            List items = sfileUpLoad.parseRequest(request); 
            Iterator it = items.iterator(); 
            //暫時隻考慮單文件 
            while(it.hasNext()){ 
                FileItem fileItem = (FileItem)it.next(); 
                if(!fileItem.isFormField()){ 
                    inputStream = fileItem.getInputStream(); 
                    filesize = fileItem.getSize(); 
                    bs = new byte[(int)filesize]; 
                     
                }else{ 
                    if (fileItem.getFieldName().equals("width")) { 
                        dfo = (DeferredFileOutputStream) fileItem.getOutputStream(); 
                        width = Integer.parseInt(new String(dfo.getData())); 
                    } 
                    if (fileItem.getFieldName().equals("height")) { 
                        dfo = (DeferredFileOutputStream) fileItem.getOutputStream(); 
                        height = Integer.parseInt(new String(dfo.getData())); 
                    } 
                } 
            } 
             
            op = ResizeImg(inputStream, width, height); 
             
            bs = op.toByteArray(); 
             
            String imgpath = "data:image/jpeg;base64," ; 
            String img = encoder.encode(bs); 
             
            imgpath += img; 
             
            return imgpath; 
        }catch (FileUploadException e) { 
            e.printStackTrace(); 
            LOGGER.error(e); 
        } catch (IOException e) { 
            e.printStackTrace(); 
            LOGGER.error(e); 
        }finally{ 
            if(dfo != null){ 
                dfo.close(); 
            } 
            if(inputStream != null){ 
                inputStream.close(); 
            } 
            if(op!= null){ 
                op.close(); 
            } 
        } 
         
        //blankimage 
        return "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="; 
         
    } 
     
    //隻對jpg縮放 
    public ByteArrayOutputStream ResizeImg(InputStream inputStream,int maxWidth,int maxHeight) throws IOException{ 
         
        BufferedImage bufferimage = ImageIO.read(inputStream); 
        int curWidth = bufferimage.getWidth(); 
        int curHeight = bufferimage.getHeight(); 
         
//      double desiredRatio = Math.min((double)(maxWidth)/(double)curWidth,(double)maxHeight/(double)curHeight); 
//      curWidth =  (int) (curWidth*desiredRatio); 
//      curHeight = (int)(curHeight*desiredRatio); 
        double ratio = 0;  
        Image itemp = bufferimage.getScaledInstance(maxWidth, maxHeight, bufferimage.SCALE_SMOOTH);       
        // 計算比例       
        if ((bufferimage.getHeight() > maxHeight) || (bufferimage.getWidth() > maxWidth)) {       
            if (bufferimage.getHeight() > bufferimage.getWidth()) {       
                ratio = (new Integer(maxHeight)).doubleValue() / bufferimage.getHeight();       
            } else {       
                ratio = (new Integer(maxWidth)).doubleValue() / bufferimage.getWidth();       
            }       
            AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);       
            itemp = op.filter(bufferimage, null);       
        } 
         
         
        BufferedImage bufftmp = new BufferedImage(curWidth,curHeight,BufferedImage.TYPE_INT_RGB); 
        Graphics2D g2D = bufftmp.createGraphics(); 
         
        g2D.setColor(Color.white); 
        g2D.fillRect(0, 0, curWidth, curHeight); 
//      g2D.drawImage(bufferimage, null, 0, 0); 
         
        if (maxWidth == itemp.getWidth(null))       
            g2D.drawImage(itemp, 0, (maxHeight – itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);       
        else      
            g2D.drawImage(itemp, (maxWidth – itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);       
        g2D.dispose();       
//        itemp = bufftmp; 
         
        ByteArrayOutputStream op = new ByteArrayOutputStream(); 
         
        JPEGImageEncoder imageEncoder = JPEGCodec.createJPEGEncoder(op); 
         
        imageEncoder.encode((BufferedImage)itemp); 
         
        return op; 
    } 
     
 

viewImg.jsp:
Html代碼 
<%@ page language="java"  pageEncoding="UTF-8"%> 
<%@page import="com.common.controller.ImagePreview;"%> 
<% 
ImagePreview img = new ImagePreview(); 
out.write(img.ProcessRequest(request)); 
%> 


下面是截圖:

作者“zhanghouyin-hotmail-com”
 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *