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

时间:2020-12-23 07:08:10

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:%;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=/^\+?[-][-]*$/;
var kd = $("#pdtpNewForm #kd");
if(!regl.test(kd.val())){
alert("宽度应该为正整数!");
kd.focus();
return false;
}
if(parseInt(kd.val())>){
alert("宽度不能超过225!");
kd.focus();
return false;
}
var gd = $("#pdtpNewForm #gd");
if(!regl.test(gd.val())){
alert("宽度应该为正整数!");
gd.focus();
return false;
}
if(parseInt(gd.val())>){
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: , maxHeight: , 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="">
<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="" cellpadding="" cellspacing="" 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="" readonly="true" value="${zzdm }" maxlength="" />
</td>
<td width="225px" rowspan="">
<table border="" cellpadding="" cellspacing="">
<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="" 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="" readonly="true" value="${bmdm }" maxlength="" />
</td>
</tr>
<tr>
<td width="70px">
<label for="tpbt"><%=WzXxfbPdtp.ALIAS_TPBT%>:</label>
</td>
<td width="120px">
<form:input path="tpbt" id="tpbt" size="" cssClass="required" maxlength="" />
</td>
</tr>
<tr>
<td width="70px">
<label for="tplj"><%=WzXxfbPdtp.ALIAS_TPLJ%>:</label>
</td>
<td width="120px">
<form:input path="tplj" id="tplj" size="" cssClass="required" maxlength="" />
</td>
</tr>
<tr>
<td width="70px">
图片宽高:
</td>
<td width="120px">
<table>
<tr>
<td>
<input id="kd_tem" name="kd_tem" value="" onchange="javascript:changeValue('kd');" size="" maxlength="">
<input type="hidden" id="kd" name="kd" value="">
</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="" size="" maxlength="" onchange="javascript:changeValue('gd');">
<input type="hidden" id="gd" name="gd" value="">
</td>
<td>&nbsp;&nbsp;单位(px)</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="" width="190px">
<label for="sfpd"><%=WzXxfbPdtp.ALIAS_SFPD%>:</label>
<label><input type="radio" name="sfpd" value="" checked="checked">飘动</label>
<label><input type="radio" name="sfpd" value="">不飘动</label>
</td>
<td><font color="red">只允许上传1M内jpg,jpeg,gif,png格式图片</font></td>
</tr>
<tr>
<td width="70px">选择图片</td>
<td colspan=""><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>(*)){
message="文件"+item.getName()+"大超过了1M,上传失败!";
break;
}
// 扩展名格式:
if (name.lastIndexOf(".") >= ) {
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>(*)){
message="文件"+item.getName()+"大超过了1M,上传失败!";
break;
}
// 扩展名格式:
if (name.lastIndexOf(".") >= ) {
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(, path.lastIndexOf("/"));
//得到图片的名称
String name = path.substring(path.lastIndexOf("/")+);
//得到图片存放的完整路径
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 = ; i < arr_items.length; i++) {
pdtp = wzXxfbPdtpManager.getById(arr_items[i]);
wzXxfbPdtpManager.removeById(arr_items[i]);
String path = pdtp.getTpdz();
//得到图片存放的完整路径
String folder = path.substring(, path.lastIndexOf("/"));
//得到图片的名称
String name = path.substring(path.lastIndexOf("/")+);
//得到图片存放的完整路径
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", "");
/**
* 返回后需要刷新的 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 = ; DiskFileItemFactory factory = new DiskFileItemFactory(); int width = ;
int height = ; InputStream inputStream = null;
ByteArrayOutputStream op = null;
DeferredFileOutputStream dfo = null; try{
factory.setSizeThreshold();// 设置缓冲,这个值决定了是fileinputstream还是bytearrayinputstream
//factory.setRepository(new File("d:\\temp"));//设置临时存放目录,默认是new File(System.getProperty("java.io.tmpdir"))
ServletFileUpload sfileUpLoad = new ServletFileUpload(factory);
sfileUpLoad.setSizeMax(**);//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 = ;
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(, , curWidth, curHeight);
// g2D.drawImage(bufferimage, null, 0, 0); if (maxWidth == itemp.getWidth(null))
g2D.drawImage(itemp, , (maxHeight - itemp.getHeight(null)) / , itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
else
g2D.drawImage(itemp, (maxWidth - itemp.getWidth(null)) / , , 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));
%>

下面是截图:

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