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">
        <div class="pageContent" layoutH="30">
        <div 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>
                                    <div style="width: 225px;height: 170px;border:1px solid #99BBE8">
                                        <table border="0" class="perview">
                                            <tr>
                                                <td align="center"><img id="idImg"/></td>
                                            </tr>
                                        </table>
                                    </div>
                                </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>
        </div>
        </div>
        <iframe name="hidden_frame" id="hidden_frame" src="message.html" style="display:none"></iframe>
        <div class="formBar">
            <ul>
                <li>
                    <div class="buttonActive"><div class="buttonContent"><button type="submit"  onclick="return checkPdtpSubmit();">保存</button></div></div>
                </li>
                <li>
                    <div class="button"><div class="buttonContent"><button type="button" class="close">关闭</button></div></div>
                </li>
            </ul>
        </div>
    </form:form> 

2 后台Controller

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));
%> 

下面是截图:

时间: 2024-10-04 01:04:29

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

文件上传之图片预览

一.业界现状分析 有时候我们需要在上传图片之前为用户提供图片预览的功能,HTML5规范出来之前,由于缺少原生的File API支持,我们需要借助Flash或者浏览器插件来满足这种需求.有了HTML5,我们可使用URL或者FileReader对象实现预览功能. 二.应用场景 图片分享类的应用,如Flickr,Facebook.相册应用,如:QQ相册. 虽然139邮箱没有合适的应用场景,但是可将技术预研的成果作为技术储备,好东西总有用得着的时候. 三.编码实现 方式一:window.URL (1).

input实现多文件上传及图片预览

通过使用html的input标签可以实现文件上传比如 <input id="file" type="file" name="upload" multiple onchange="showch();"> 其中将type属性设为file. 添加multiple实现多文件上传入下图所示: 通过使用原生js或jQuery就可以获得文件名,文件路径,文件大小等属性 获得文件属性的js代码如下: <script type

2016/4/19 ①单个文件上传 ②上传图片后 预览图片

1,f1.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <!-- 作业:在网上找上传图片预览的代码 上传服务器 再预览--> <form action="f1chuli.php&q

input 文件上传实现本地预览

上传图片 本地预览 获取图片大小 上传视频 本地预览 获取视频 duration 视频大小 图片上传 主要涉及内容 input accept filesList URL.createObjectURL() URL.revokeObjectURL() input file <label for='upload'></label> // ::before :: after 用于扩展可点击区域 <input type="file" id="upload

用openoffice+jodconverter+webuploader+pdf.js实现文件上传、在线预览功能

一.背景 最近公司一个项目要实现一个文件上传以及多文档在线预览的功能,之前一直做无线工具开发的,没有涉及到这些东西.另外项目组缺java开发人员,而且自己也只是一个半吊子前端加小半吊子java开发人员,所以让我一个人先弄个Demo出来瞧瞧.在网上搜索了不少资料,在这里只是整理一下,留作以后查阅. 二.插件以及工具包 1.pdfjs-v1.7.225  前端pdf格式文件的显示组件 2.webuploader-0.1.5  百度的文件上传组件 3.video-js-6.2.5 html5视频播放组

WebForm实现文件上传,并预览

实现效果: 页面代码: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat=&quo

文件上传(无预览模式版)

文件上传是网页的基本功能之一,这一章我们将讲解无预览模式版本 第一:网页表单显示 <body> <h1>文件上传</h1> <form action="chuli.php" method="post" enctype="multipart/form-data"> <input type="file" name="file"/> <input

文件上传(带有预览模式)

这里所讲的预览是将文件上传至后台之后,代码调用服务器端文件,在网页中显示出来 第一:网页显示部分 和  显示区域css样式表 <body> <h1>文件上传</h1> <form action="chuli.php" method="post" enctype="multipart/form-data" id="sc" target="hidden_frame"&g

php文件上传及头像预览

php文件上传原理是通过form表单的enctype="multipart/form-data"属性将文件临时放到wamp文件夹中的tmp目录下,再通过后台php 程序将文件保存在体统中. html代码: 1 <form action="shangchuan.php" method="post" enctype="multipart/form-data"> 2 <input type="file&q