您的位置:首页 > Web前端 > JQuery

spring mvc+jquery uploadify3.1上传

2013-08-04 13:32 507 查看
最近看到一个用jquery uploadify上传的例子,然后自己把它和spring mvc整合了一下,废话不多说,图码一起上

自己去下载jquery uploadify这个插件,后台需要引入commons-io.jar和commons-fileupload.jar包,其spring mvc环境就自己去搭啦

这是uploadify的上传效果.



下面上代码:

前台页面,还有具体参数的说明

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'upload.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">

<link rel="stylesheet" href="uploadify/uploadify.css" type="text/css"></link>
<script type="text/javascript" src="uploadify/jquery-1.7.2.min.js"></script>
<script type="text/javascript"
src="uploadify/jquery.uploadify-3.1.min.js"></script>

<script type="text/javascript">
$(function() {
$("#multiple_file_upload").uploadify({
'uploader' : 'upload100.do',//************ action **************
'height' : 27,//表示按钮的高度,默认30PX。若要改为50PX,如下设置:'height' : 50,
'width' : 50,//表示按钮的宽度
'buttonText' : '浏 览',//按钮上显示的文字,默认”SELECT FILES”
'buttonCursor' : 'hand',//上传按钮Hover时的鼠标形状,默认值是’hand’
'auto' : false, //是否自动开始
'multi' : true, //是否支持多文件上传,默认为true
'method' : 'post',//默认是’post’,也可以设置为’get’
'swf' : 'uploadify/uploadify.swf',//进度条显示文件
'cancelImg' : 'uploadify/uploadify-cancel.png',//取消按钮的图片
'fileTypeDesc' : 'jpg、png、gif、bmp',//允许上传的文件类型的描述,在弹出的文件选择框里会显示
'fileTypeExts' : '*.jpg;*.png;*.gif;*.bmp;*.doc;*.txt',//指定文件格式
'fileSizeLimit' : '50MB',//上传文件大小限制,默认单位是KB,若需要限制大小在100KB以内,可设置该属性为:'100KB'
'fileObjName' : 'myFile',//文件对象名称。用于在服务器端获取文件。
'formData' : {
'userName' : 'willwind',
'content' : 'aaaaaaaaaaaaaaaaaaaaaaaaaa'
},
'progressData' : 'all', // 'percentage''speed''all'//队列中显示文件上传进度的方式:all-上传速度+百分比,percentage-百分比,speed-上传速度
'preventCaching' : true,//若设置为true,一个随机数将被加载swf文件URL的后面,防止浏览器缓存。默认值为true
'timeoutuploadLimit' : 5,//能同时上传的文件数目
'removeCompleted' : true,//默认是True,即上传完成后就看不到上传文件进度条了。
'removeTimeout' : 5,//上传完成后多久删除队列中的进度条,默认为3,即3秒。
'requeueErrors' : true,//若设置为True,那么在上传过程中因为出错导致上传失败的文件将被重新加入队列。
'successTimeout' : 30,//表示文件上传完成后等待服务器响应的时间。不超过该时间,那么将认为上传成功。默认是30,表示30秒。
'uploadLimit' : 999,//最多上传文件数量,默认999
'onUploadStart' : function(file) {
//$("#file_upload").uploadify("settings", "formData", {'userName':name,'qq':qq});
//$("#file_upload").uploadify("settings", "buttonText", "aaa");
//alert(file.name + " is ready to go!")
$("#stopUpload").removeAttr("hidden");
},
'onUploadSuccess' : function(file, data, response) {
//alert(file.name + " upload success !");
//alert(data + "----" + response);
$("#stopUpload").attr("hidden",true);
}

});
});
</script>

</head>

<body>
<div align="center">
<input type="file" name="uploadify" id="multiple_file_upload" />
<hr>
<a href="javascript:$('#multiple_file_upload').uploadify('upload','*')">开始上传</a>
<a href="javascript:$('#multiple_file_upload').uploadify('cancel','*')">取消上传</a>
<a href="javascript:$('#multiple_file_upload').uploadify('stop','*')" hidden=true id="stopUpload">停止上传</a>
</div>
</body>
</html>


后台代码:

在spring mvc的配置文件上加上一下代码,bean一定要是multipartResolver,提交时会先去找这个bean

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>


java代码:这是文件上传和图片上传(生成缩略图)的工具,没有将代码封装,你可以自己去封装

/**
* @ClassName: FileUpload
* @author YangXuan
* @date Aug 4, 2013 1:27:00 PM
*
*/
@Controller
public class FileUpload extends HttpServlet {

/**
* @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么)
*/
private static final long serialVersionUID = 1L;
private final String uploadLocation = "fileupload\\";
private final String imageLocation = "images\\";
private final String otherLocation = "others\\";
private final String imageThumnailLoation = "thumnail\\";

@RequestMapping(value = "/upload100.do", method = RequestMethod.POST)
@ResponseBody
public String upload(HttpServletRequest request,
HttpServletResponse response) throws IOException {

MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 获取前台传值
String[] userNames = multipartRequest.getParameterValues("userName");
String[] contents = multipartRequest.getParameterValues("content");
String userName = "";
String content = "";
if (userNames != null) {
userName = userNames[0];
System.out.println("userName:" + userName);
}
if (contents != null) {
content = contents[0];
System.out.println("content:" + content);
}
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
// 上传到服务端的路径
String ctxPath = request.getSession().getServletContext()
.getRealPath("/")
+ uploadLocation;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
String ymd = sdf.format(new Date());

String originalFileName = null;
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
// 上传文件名
System.out.println("key: " + entity.getKey());
System.out.println("value: " + entity.getValue());

MultipartFile mf = entity.getValue();
originalFileName = mf.getOriginalFilename();
String fileExt = originalFileName.substring(
originalFileName.lastIndexOf(".") + 1).toLowerCase();

// new file name
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_HHmmss");
String newFileName = df.format(new Date()) + "_"
+ suijiString.randomString(6) + "." + fileExt;

// 是image则进入此处开始执行
if (fileExt.equals("jpg") || fileExt.equals("png")) {

// 创建image文件夹,字目录按日期来分
String uploadFolder = ctxPath + imageLocation + ymd + "/";
File imageFile = new File(uploadFolder);
if (!imageFile.exists()) {
imageFile.mkdirs();
}
String uploadFileLocation = uploadFolder + newFileName;
if (this.htmlUpload(mf.getInputStream(), uploadFileLocation)) {
System.out.println(" ------- image upload success");

// 如果图片上传成功,那么就要生成缩略图
String thumnailFileName = "thum_" + newFileName;
String uploadFolder2 = ctxPath + imageLocation
+ imageThumnailLoation + ymd + "/";
File imageThumnailFile = new File(uploadFolder2);
if (!imageThumnailFile.exists()) {
imageThumnailFile.mkdirs();
}
BufferedImage bi = ImageIO.read(mf.getInputStream());
if (bi != null) {
String uploadFileLocation2 = uploadFolder2
+ thumnailFileName;
if (this.uploadJPGfile(bi, uploadFileLocation2)) {
System.out
.println(" ------- generate thumnail success");
} else {
System.out
.println(" ------- generate thumnail fail");
}
}
return "image file upload success";
} else {
System.out.println(" ------- image upload fail");
return "image file upload fail";
}
}
// 不是image则调到此处开始执行
else {
// 创建others文件夹,字目录按日期来分
String uploadFolder3 = ctxPath + otherLocation + ymd + "/";
File otherFile = new File(uploadFolder3);
if (!otherFile.exists()) {
otherFile.mkdirs();
}
String uploadFileLocation = uploadFolder3 + newFileName;
if (this.htmlUpload(mf.getInputStream(), uploadFileLocation)) {
System.out.println(" ------- other upload success");
return "other file upload success";
} else {
System.out.println(" ------- other upload fail");
return "other file upload fail";
}
}

}
return null;
}

/**
* @Title: htmlUpload
* @param @param inputStream	传进一个流
* @param @param uploadFile		服务端输出的路径和文件名
* @return boolean    返回类型
* @throws
*/
private boolean htmlUpload(InputStream inputStream, String uploadFile) {
try {
byte[] buff = new byte[4096]; // 缓冲区
FileOutputStream output = new FileOutputStream(uploadFile); // 输出流
int bytecount = 1;
while ((bytecount = inputStream.read(buff, 0, 4096)) != -1) { // 当input.read()方法,不能读取到字节流的时候,返回-1
output.write(buff, 0, bytecount); // 写入字节到文件
}
output.flush();
output.close();
return true;
} catch (Exception e) {
return false;
}
}

/**
* @Title: uploadJPGfile
* @param @param img
* @param @param uploadFileLocation2	服务端输出的路径和文件名
* @return boolean    返回类型
* @throws
*/
public boolean uploadJPGfile(BufferedImage img, String uploadFileLocation2) {
try {
// 转为jpg标准格式//
if (img != null) {
int new_w = 150;
int new_h = 100;
BufferedImage tag = new BufferedImage(new_w, new_h,
BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(img, 0, 0, new_w, new_h, null); // 绘制缩小后的图
FileOutputStream out = new FileOutputStream(uploadFileLocation2);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
return true;
} else {
return false;
}
} catch (Exception e) {
System.out.println("异常错误!");
return false;
}
}
}


*****************************
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: