欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

dwz+jquery+fileupload+springmvc实现文件上传及图片预览

程序员文章站 2022-07-08 14:10:36
1 前台jsp:文件的上传利用了iframe实现局部刷新功能。使用了apache的fileupload组件,用到的jar: commons-fileupload.jar,co...

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()){