首先我们来讲讲前端的页面代码如何写:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="charset=utf-8" />
<title>图片异步上传</title>
<!--导入jq文件和样式文件-->
<script src="js/jquery-1.9.1.min.js"></script>
<link href="bootstrap/css/bootstrap.css" rel="stylesheet" />
<script type="text/javascript">
/*图片上传*/
function UploadImage(){
$("#UploadInput").click();
}
function doUpload(){
$("#imageForm").submit();
}
function getValS(){
var filePath = $("iframe").contents().find("#filePath").val();
var msg = $("iframe").contents().find("#msg").val();
if(filePath == "" || filePath == undefined){
}else{
$("#BACKGROUND").val(filePath);
}
if(msg == "1"){
bootbox.alert("请上传图片类型文件", function(result) {});
}else if(msg == "2"){
bootbox.alert("文件名中含有非法字符", function(result) {});
}
fimg();
}
</script>
</head>
<body>
<div style="width:100%;top: 50%;position: absolute;top: 50%;height: 240px;margin-top: -120px;" align="center">
<table border="1" cellspacing="0" class="tb">
<td colspan="3">
<div class="span3" id="fimg" style="margin-bottom:5px;width:65%;height:160px;">
<img src="/">
</div>
<div class="show fileupload fileupload-new" data-provides="fileupload" >
<input type="text" id="BACKGROUND" name="BACKGROUND" style="margin-bottom: 0px;" class="span6" value="">
<input type="button" οnclick="UploadImage()" value="上传" class="btn btn-default btn-file" >
</div>
</td>
</table>
</div>
<iframe id='frameFile' src="/Upload.chtm" name='frameFile' style='display: none;' οnlοad="getValS();"></iframe>
<form target='frameFile' action="/saveImage.chtm" method="post" id="imageForm" enctype="multipart/form-data">
<input id="UploadInput" style="display: none" type="file" name="titleImage" οnchange="doUpload()"/>
<input type="hidden" name="FILE_PATH" value="/upload/live/">
</form>
</body>
<script type="text/javascript">
function fimg(){
var fimg = $("#BACKGROUND").val();
var html = "<img style='height: 100%;' src='/"+fimg+"'>";
document.getElementById("fimg").innerHTML=html;
}
fimg();
</script>
</html>
点击上传按钮后执行UploadImage() 函数进行模拟点击 $("#UploadInput").click();进行表单提交$("#imageForm").submit();
当选择图片后会执行doUpload() 函数进行表单提交$("#imageForm").submit();
@Controller
public class CommonController {
private String filePath = "";
//保存图片
@RequestMapping(value="/saveImage.chtm")
public String saveImage(@RequestParam("titleImage") MultipartFile file,
HttpServletRequest request, javax.servlet.http.HttpServletResponse response,HttpSession session,Model model)
throws IOException{
Map<String, Object> map = new HashMap<String , Object>();
String flag = request.getParameter("flag");
map = uploadFile(file, request,session);//核心代码
filePath=map.get("filePath").toString();
String msg = map.get("msg").toString();
System.out.println("filePath:"+filePath);
model.addAttribute("filePath", filePath);
model.addAttribute("msg", msg);
model.addAttribute("flag", flag);
filePath = "";
return "common/upLoad";
}
@RequestMapping(value="/Upload.chtm")
public String UploadImg(Model model){
model.addAttribute("filePath", filePath);
model.addAttribute("msg", "4");
filePath = "";
return "common/upLoad";
}
//上传图片
public Map<String,Object> uploadFile(MultipartFile file,
HttpServletRequest request ,HttpSession session) throws IOException {
Map<String, Object> map = new HashMap<String , Object>();
String FILE_PATH = request.getParameter("FILE_PATH");
//<input type="hidden" name="FILE_PATH" value="/upload/live/">设置图片的文件夹
String FILE_PATHS = request.getRealPath(request.getRequestURI()).
replace("\\", "/").replace("/weixin/saveImage.chtm", "") + FILE_PATH;//最后获取的是服务器路径并且拼接了文件夹
String fileName = file.getOriginalFilename(); //获取图片名称
String[] aa = fileName.split("\\.");
String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
Pattern p = Pattern.compile(regEx);
String result="1";
for (int i = 0; i < aa.length-1; i++) {
Matcher m = p.matcher(aa[i]);
if(m.find()){
result ="2";
}
}
int j= aa.length-1;
String username = "img"+CustomStatic.getUniqueId();//CustomStatic.getUniqueId()获取一个当前时间的时间戳拼接的字符串
File tempFile = new File(FILE_PATHS, username +"." + String.valueOf(aa[j]));//aa[j]是文件后缀
if(result.equals("1")){
if(aa.length>1){
if(aa[j].equals("jpg")||aa[j].equals("png") ||aa[j].equals("PNG")|| aa[j].equals("JPG") ){
if (!tempFile.getParentFile().exists()) {
tempFile.getParentFile().mkdir();
}
if (!tempFile.exists()) {
tempFile.createNewFile();
}
file.transferTo(tempFile); //到这一步图片已经成功上传到tomcat服务器下
map.put("filePath", FILE_PATH+ tempFile.getName());//
map.put("msg", "4");
return map;//返回回一个map对象
}else{
map.put("filePath", "");
map.put("msg", "1");
return map;
}
}else{
map.put("filePath", "");
map.put("msg", "3");
return map;
}
}else{
map.put("filePath", "");
map.put("msg", "2");
return map;
}
}
}
如果成功的话我们在页面上f12查看iframe标签可以看到这样的值
因为重新刷新了iframe的值所以会执行getValS()函数。
获取iframe里面的id为filePath的值==var filePath = $("iframe").contents().find("#filePath").val();
js得写法是document.getElementById('frameFile').contentWindow.document.getElementById('filePath').value;
然后给id为BACKGROUND的input赋值:$("#BACKGROUND").val(filePath);
最后执行fimg函数刷新图片
var fimg = $("#BACKGROUND").val();
var html = "<img style='height: 100%;' src='/"+fimg+"'>";
document.getElementById("fimg").innerHTML=html;
下面附上完整的jsp代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="charset=utf-8" />
<title>图片异步上传</title>
<script src="<%=path%>/js/jquery-1.9.1.min.js"></script>
<!-- Bootstrap -->
<link href="<%=path%>/bootstrap/css/bootstrap.css" rel="stylesheet" />
<script type="text/javascript">
/*图片上传*/
function UploadImage(){
$("#UploadInput").click();
}
function doUpload(){
$("#imageForm").submit();
}
function getValS(){
var filePath = $("iframe").contents().find("#filePath").val();
var msg = $("iframe").contents().find("#msg").val();
if(filePath == "" || filePath == undefined){
}else{
$("#BACKGROUND").val(filePath);
}
if(msg == "1"){
bootbox.alert("请上传图片类型文件", function(result) {});
}else if(msg == "2"){
bootbox.alert("文件名中含有非法字符", function(result) {});
}
fimg();
}
</script>
</head>
<body>
<div style="width:100%;top: 50%;position: absolute;top: 50%;height: 240px;margin-top: -120px;" align="center">
<table border="1" cellspacing="0" class="tb">
<td colspan="3">
<div class="span3" id="fimg" style="margin-bottom:5px;width:65%;height:160px;">
<img src="<%=path%>/${setWordList.get(0).get('BACKGROUND')}">
</div>
<div class="show fileupload fileupload-new" data-provides="fileupload" >
<input type="text" id="BACKGROUND" name="BACKGROUND" style="margin-bottom: 0px;" class="span6" value="${setWordList.get(0).get('BACKGROUND') }">
<input type="button" οnclick="UploadImage()" value="上传" class="btn btn-default btn-file" >
</div>
</td>
</table>
</div>
<iframe id='frameFile' src="<%=path%>/Upload.chtm" name='frameFile' style='display: none;' οnlοad="getValS();"></iframe>
<form target='frameFile' action="<%=path%>/saveImage.chtm" method="post" id="imageForm" enctype="multipart/form-data">
<input id="UploadInput" style="display: none" type="file" name="titleImage" οnchange="doUpload()"/>
<input type="hidden" name="FILE_PATH" value="/upload/live/">
</form>
</body>
<script type="text/javascript">
function fimg(){
var fimg = $("#BACKGROUND").val();
var html = "<img style='height: 100%;' src='<%=path%>"+fimg+"'>";
document.getElementById("fimg").innerHTML=html;
}
fimg();
</script>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<input type="hidden" value="${filePath}" id="filePath">
<input type="hidden" value="${msg}" id="msg">
<input type="hidden" value="${flag}" id="flag">