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:%;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> 单位(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> 单位(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实现文件上传 及图片预览的更多相关文章
- jsp+springmvc实现文件上传、图片上传和及时预览图片
1.多文件上传:http://blog.csdn.net/a1314517love/article/details/24183273 2.单文件上传的简单示例:http://blog.csdn.net ...
- php文件上传及头像预览
php文件上传原理是通过form表单的enctype="multipart/form-data"属性将文件临时放到wamp文件夹中的tmp目录下,再通过后台php 程序将文件保存在 ...
- javascript实现文件上传之前的预览功能
1.首先要给上传文件表单控件和图片控件设置name属性 <div class="form-group"> <label fo ...
- HTML5文件上传前本地预览
HTML5之FileReader的使用 HTML5定义了FileReader作为文件API的重要成员用于读取文件,根据W3C的定义,FileReader接口提供了读取文件的方法和包含读取结果的事件模型 ...
- SpringMVC+ajax文件上传实例教程
原文地址:https://blog.csdn.net/weixin_41092717/article/details/81080152 文件上传文件上传是项目开发中最常见的功能.为了能上传文件,必须将 ...
- springmvc实现文件上传
springmvc实现文件上传 多数文件上传都是通过表单形式提交给后台服务器的,因此,要实现文件上传功能,就需要提供一个文件上传的表单,而该表单就要满足以下3个条件 (1)form表彰的method属 ...
- 6.学习springmvc的文件上传
一.文件上传前提与原理分析 1.文件上传必要前提: 2.文件上传原理分析: 3.需要引入的jar包: 二.传统方式文件上传程序 1.pom.xml <dependency> <gro ...
- 使用springmvc实现文件上传
该配置在javaweb上传文件篇中的基础上进行配置:https://www.cnblogs.com/flypig666/p/11745182.html 1.配置文件解析器,在springmvc.xml ...
- 【SpringMVC】SpringMVC 实现文件上传
SpringMVC 实现文件上传 文章源码 文件上传回顾 查看 JavaWeb 阶段的文件上传下载 实现步骤: 客户端: 发送 post 请求,告诉服务器要上传什么文件 服务器: 要有一个 form ...
随机推荐
- Hdu 1158 Employment Planning(DP)
Problem地址:http://acm.hdu.edu.cn/showproblem.php?pid=1158 一道dp题,或许是我对dp的理解的还不够,看了题解才做出来,要加油了. 只能先上代码了 ...
- CreateFile函数使用方法详细介绍
CreateFileThe CreateFile function creates or opens the following objects and returns a handle that c ...
- 对base-adapter-helper的简单分析
在微博上看到了这篇Android ListView适配器应该这样写,受益匪浅. 于是依据文章结尾的介绍来到了base-adapter-helper的github,地址:https://github.c ...
- ADB logcat 过滤方法(抓取日志)
1. Log信息级别 Log.v- VERBOSE : 黑色 Log.d- DEBUG : 蓝色 Log.i- INFO : 绿色 Log.w- WARN : 橙色 Log.e- ERROR ...
- Image控件
前台代码: <asp:Image ID="Image1" runat="server" /> 后台代码; protected void Page_L ...
- 我的Python成长之路---第一天---Python基础(作业1:登录验证)---2015年12月26日(雾霾)
作业一:编写登录接口 输入用户名密码 认证成功系那是欢迎信息 输错三次后锁定 思路: 1.参考模型,这个作业我参考了linux的登录认证流程以及结合网上银行支付宝等锁定规则 1)认证流程参考的是Lin ...
- OC补充
OC 1成员变量默认初始化为0 2匿名对象:就是没有名字的对象,比如:(不建议使用) 3 [Car new]->speed = 300; [[Car new] run];(运行结果speed为0 ...
- WCF技术剖析之二十八:自己动手获取元数据[附源代码下载]
原文:WCF技术剖析之二十八:自己动手获取元数据[附源代码下载] 元数据的发布方式决定了元数据的获取行为,WCF服务元数据架构体系通过ServiceMetadataBehavior实现了基于WS-ME ...
- 黑龙江省第七届大学生程序设计竞赛-Mysterious Organization
描述 GFW had intercepted billions of illegal links successfully. It has much more effect. Today, GFW i ...
- Convert SVG to PNG in Python - Stack Overflow
Convert SVG to PNG in Python - Stack Overflow Convert SVG to PNG in Python