JQuery Uploadify v3.2.1 上传图片并预览(基于spring mvc框架开发)
2016-07-29 21:17
621 查看
http://blog.csdn.net/java0311/article/details/44885933
Controller后台处理:
[java] view
plain copy
package com.news.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
@Controller
@RequestMapping("/upload")
public class UpLoadIMGController {
@RequestMapping("/uploadIMG")
public void uploadIMG(HttpServletRequest request, HttpServletResponse response) throws Exception{
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
String ctxPath=request.getSession().getServletContext().getRealPath("/")+"uploadFiles";
ctxPath += File.separator;
// 创建文件夹
File file = new File(ctxPath);
if (!file.exists()) {
file.mkdirs();
}
String fileName = null;
String newName = null;
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
// 上传文件
MultipartFile mf = entity.getValue();
fileName = mf.getOriginalFilename();//获取原文件名
//获得当前时间的最小精度
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
newName = format.format(new Date());
//获得三位随机数
Random random = new Random();
for(int i = 0; i < 3; i++){
newName = newName + random.nextInt(9);
}
File uploadFile = new File(ctxPath + newName+fileName.substring(fileName.lastIndexOf(".")));
try {
FileCopyUtils.copy(mf.getBytes(), uploadFile);
} catch (IOException e){
e.printStackTrace();
}
}
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(newName+fileName.substring(fileName.lastIndexOf(".")));
}
@RequestMapping("/getImg")
public void getImg(HttpServletRequest request, HttpServletResponse response) throws Exception{
String file = request.getParameter("file");
String path = request.getSession().getServletContext().getRealPath("/")+"uploadFiles"+File.separator+file;
File pic = new File(path);
FileInputStream fis = new FileInputStream(pic);
OutputStream os = response.getOutputStream();
try {
int count = 0;
byte[] buffer = new byte[1024 * 1024];
while ((count = fis.read(buffer)) != -1)
os.write(buffer, 0, count);
os.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null)
os.close();
if (fis != null)
fis.close();
}
}
}
jsp前台:
[html] view
plain copy
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.11.1.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.uploadify.min.js"></script>
<link href="${pageContext.request.contextPath}/css/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function() {
$("#upload_org_code").uploadify({
'height' : 27,
'width' : 80,
'buttonText' : '选择图片',
'swf' : '${pageContext.request.contextPath}/css/uploadify.swf',
'uploader' : '${pageContext.request.contextPath}/upload/uploadIMG',
'auto' : true,
'multi' : false,
'removeCompleted':false,
'cancelImg' : '${pageContext.request.contextPath}/js/uploadify-cancel.png',
'fileTypeExts' : '*.jpg;*.jpge;*.gif;*.png',
'fileSizeLimit' : '1MB',
'fileObjName' : 'file',
'onUploadSuccess':function(file,data,response){
$('#' + file.id).find('.data').html('');
$("#upload_org_code_name").val(encodeURI(data));
$("#upload_org_code_img").attr("src","${pageContext.request.contextPath}/upload/getImg?file="+encodeURI(data));
$("#upload_org_code_img").show();
},
//加上此句会重写onSelectError方法【需要重写的事件】
'overrideEvents': ['onSelectError', 'onDialogClose'],
//返回一个错误,选择文件的时候触发
'onSelectError':function(file, errorCode, errorMsg){
switch(errorCode) {
case -110:
alert("文件 ["+file.name+"] 大小超出系统限制的" + jQuery('#upload_org_code').uploadify('settings', 'fileSizeLimit') + "大小!");
break;
case -120:
alert("文件 ["+file.name+"] 大小异常!");
break;
case -130:
alert("文件 ["+file.name+"] 类型不正确!");
break;
}
},
});
})
</script>
</head>
<body>
<table>
<tr>
<td align="right"><font style="color: red;">*</font>组织代码机构:</td>
<td>
<table>
<tr>
<td width="45%"><input type="file" name="upload_org_code" id="upload_org_code"/></td>
<td><img style="display: none" id="upload_org_code_img" src="" width="150" height="150"></td>
</tr>
</table>
<input type="hidden" name="upload_org_code_name" id="upload_org_code_name" />
<hr>
</td>
</tr>
</table>
</body>
</html>
特别注意:
[html] view
plain copy
$("#upload_org_code_img").attr("src","${pageContext.request.contextPath}/upload/getImg?file="+encodeURI(data));
[html] view
plain copy
如果报未找到文件,不进请求方法的。请在方法处加上<span style="font-size:24px;color:#ff0000;"><strong>.do</strong></span>
[html] view
plain copy
<pre code_snippet_id="636289" snippet_file_name="blog_20150405_2_30604" name="code" class="html"> $("#upload_org_code_img").attr("src","${pageContext.request.contextPath}/upload/getImg<span style="color:#ff0000;"><strong>.do</strong></span>?file="+encodeURI(data));
Controller后台处理:
[java] view
plain copy
package com.news.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
@Controller
@RequestMapping("/upload")
public class UpLoadIMGController {
@RequestMapping("/uploadIMG")
public void uploadIMG(HttpServletRequest request, HttpServletResponse response) throws Exception{
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
String ctxPath=request.getSession().getServletContext().getRealPath("/")+"uploadFiles";
ctxPath += File.separator;
// 创建文件夹
File file = new File(ctxPath);
if (!file.exists()) {
file.mkdirs();
}
String fileName = null;
String newName = null;
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
// 上传文件
MultipartFile mf = entity.getValue();
fileName = mf.getOriginalFilename();//获取原文件名
//获得当前时间的最小精度
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
newName = format.format(new Date());
//获得三位随机数
Random random = new Random();
for(int i = 0; i < 3; i++){
newName = newName + random.nextInt(9);
}
File uploadFile = new File(ctxPath + newName+fileName.substring(fileName.lastIndexOf(".")));
try {
FileCopyUtils.copy(mf.getBytes(), uploadFile);
} catch (IOException e){
e.printStackTrace();
}
}
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(newName+fileName.substring(fileName.lastIndexOf(".")));
}
@RequestMapping("/getImg")
public void getImg(HttpServletRequest request, HttpServletResponse response) throws Exception{
String file = request.getParameter("file");
String path = request.getSession().getServletContext().getRealPath("/")+"uploadFiles"+File.separator+file;
File pic = new File(path);
FileInputStream fis = new FileInputStream(pic);
OutputStream os = response.getOutputStream();
try {
int count = 0;
byte[] buffer = new byte[1024 * 1024];
while ((count = fis.read(buffer)) != -1)
os.write(buffer, 0, count);
os.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null)
os.close();
if (fis != null)
fis.close();
}
}
}
jsp前台:
[html] view
plain copy
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.11.1.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.uploadify.min.js"></script>
<link href="${pageContext.request.contextPath}/css/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function() {
$("#upload_org_code").uploadify({
'height' : 27,
'width' : 80,
'buttonText' : '选择图片',
'swf' : '${pageContext.request.contextPath}/css/uploadify.swf',
'uploader' : '${pageContext.request.contextPath}/upload/uploadIMG',
'auto' : true,
'multi' : false,
'removeCompleted':false,
'cancelImg' : '${pageContext.request.contextPath}/js/uploadify-cancel.png',
'fileTypeExts' : '*.jpg;*.jpge;*.gif;*.png',
'fileSizeLimit' : '1MB',
'fileObjName' : 'file',
'onUploadSuccess':function(file,data,response){
$('#' + file.id).find('.data').html('');
$("#upload_org_code_name").val(encodeURI(data));
$("#upload_org_code_img").attr("src","${pageContext.request.contextPath}/upload/getImg?file="+encodeURI(data));
$("#upload_org_code_img").show();
},
//加上此句会重写onSelectError方法【需要重写的事件】
'overrideEvents': ['onSelectError', 'onDialogClose'],
//返回一个错误,选择文件的时候触发
'onSelectError':function(file, errorCode, errorMsg){
switch(errorCode) {
case -110:
alert("文件 ["+file.name+"] 大小超出系统限制的" + jQuery('#upload_org_code').uploadify('settings', 'fileSizeLimit') + "大小!");
break;
case -120:
alert("文件 ["+file.name+"] 大小异常!");
break;
case -130:
alert("文件 ["+file.name+"] 类型不正确!");
break;
}
},
});
})
</script>
</head>
<body>
<table>
<tr>
<td align="right"><font style="color: red;">*</font>组织代码机构:</td>
<td>
<table>
<tr>
<td width="45%"><input type="file" name="upload_org_code" id="upload_org_code"/></td>
<td><img style="display: none" id="upload_org_code_img" src="" width="150" height="150"></td>
</tr>
</table>
<input type="hidden" name="upload_org_code_name" id="upload_org_code_name" />
<hr>
</td>
</tr>
</table>
</body>
</html>
特别注意:
[html] view
plain copy
$("#upload_org_code_img").attr("src","${pageContext.request.contextPath}/upload/getImg?file="+encodeURI(data));
[html] view
plain copy
如果报未找到文件,不进请求方法的。请在方法处加上<span style="font-size:24px;color:#ff0000;"><strong>.do</strong></span>
[html] view
plain copy
<pre code_snippet_id="636289" snippet_file_name="blog_20150405_2_30604" name="code" class="html"> $("#upload_org_code_img").attr("src","${pageContext.request.contextPath}/upload/getImg<span style="color:#ff0000;"><strong>.do</strong></span>?file="+encodeURI(data));
相关文章推荐
- JQuery Uploadify v3.2.1 上传图片并预览(基于spring mvc框架开发)
- 基于asp.net + easyui框架,js实现上传图片之前判断图片格式,同时实现预览,兼容各种浏览器+下载
- 基于asp.net + easyui框架,js实现上传图片之前判断图片格式,同时实现预览,兼容各种浏览器+下载
- 基于asp.net + easyui框架,js实现上传图片之前判断图片格式,同时实现预览,兼容各种浏览器+下载
- 基于asp.net + easyui框架,js实现上传图片之前判断图片格式,同时实现预览,兼容各种浏览器+下载
- 基于asp.net+ easyui框架,js提交图片,实现先上传图片再提交表单
- 基于jquery实现的上传图片及图片大小验证、图片预览效果代码
- IOS开发 两、三个界面相互传值,类似android的onActivityResult(拍照上传、预览图片、点击查看、删除)
- 基于HTML5多图片Ajax上传可预览
- IOS开发 两、三个界面相互传值,类似android的onActivityResult(拍照上传、预览图片、点击查看、删除)
- 《node.js实战》案例—基于Express4.x框架的图片上传及下载的web应用
- 使用jQuery开发一个基于HTML5的漂亮图片拖拽上传web应用
- WCF开发框架形成之旅--个人图片信息的上传保存
- 基于HTML5的可预览多图片Ajax上传
- 基于Metronic的Bootstrap开发框架经验总结(5)--Bootstrap文件上传插件File Input的使用
- 基于MVC4+EasyUI的Web开发框架经验总结(8)--实现Office文档的预览
- 基于HTML5的可预览多图片Ajax上传
- 基于ajax的Html5文件上传插件,带进度并支持图片预览
- 基于MVC4+EasyUI的Web开发框架形成之旅--附件上传组件uploadify的使用
- 基于HTML5的可预览多图片Ajax上传