SpringMVC+ajaxfileupload上传
看这篇的文章之前最好看一下上篇文章这样可以更好的理解!
整个项目的基本配置和上面差不多
不同的是在webRoot文件夹下的js中引入jQuery.js 和ajaxfileupload.js
如何没有这个两个js文件可以到各自的官网下载
现在说说其他的不同之处
DemoController.java 跳转到upload.jsp
package com.iss.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/demo")
public class DemoController {
@RequestMapping("/ajaxfileupload")
public String testUpload() {
return "upload";
}
}
UserController.java
package com.iss.controller;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.iss.pojo.User;
@Controller
@RequestMapping("/user")
public class UserController {
public UserController() {
// TODO Auto-generated constructor stub
}
@RequestMapping(value="/fileupload",method=RequestMethod.POST)
public String addfile(@RequestParam("uname") String uname,
MultipartFile myfile, HttpServletRequest request,
HttpServletResponse response) throws IOException {
// 设置响应给前台的数据格式
response.setContentType("text/plain;charset=UTF-8");
// 设置响应给前台内容的PrintWriter对象
PrintWriter out = response.getWriter();
// 这里实现文件上传操作用的是commons.io.FileUtils类,它会自动判断/upload是否存在,不存在会自动创建
String realPath = request.getSession().getServletContext()
.getRealPath("/upload");
if (myfile.isEmpty()) {
out.print("1`请选择文件后上传");
out.flush();
return null;
}
// 上传前文件的名字
String originalFilename = myfile.getOriginalFilename();
try {
FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(
realPath, originalFilename));
} catch (Exception e) {
out.print("1`文件上传失败,请重试!!");
out.flush();
e.printStackTrace();
return null;
}
System.out.println(realPath + "/" + originalFilename);
out.print("0`" + request.getContextPath() + "/upload/"
+ originalFilename);
out.flush();
return null;
}
}
upload.jsp
<%@ 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" type="text/css" href="styles.css">
-->
<!--引入jQuery和ajaxfileupload-->
<script type="text/javascript" src="js/jQuery.js"></script>
<script type="text/javascript" src="js/ajaxfileupload.js"></script>
<script type="text/javascript">
function ajaxFileUpload() {
//开始上传文件时显示一个图片,文件上传完成将图片隐藏
$("#loading").ajaxStart(function(){$(this).show();}).ajaxComplete(function(){$(this).hide();});
//执行上传文件操作的函数
$.ajaxFileUpload({
//处理文件上传操作的服务器端地址(可以传参数,已亲测可用)
url : 'user/fileupload?uname=玄玉',
secureuri : false, //是否启用安全提交,默认为false
fileElementId : 'myBlogImage', //文件选择框的id属性
dataType : 'text', //服务器返回的格式,可以是json或xml等
success : function(data, status) { //服务器响应成功时的处理函数
data = data.replace(/<pre.*?>/g, ''); //ajaxFileUpload会对服务器响应回来的text内容加上<pre style="....">text</pre>前后缀
data = data.replace(/<PRE.*?>/g, '');
data = data.replace("<PRE>", '');
data = data.replace("</PRE>", '');
data = data.replace("<pre>", '');
data = data.replace("</pre>", ''); //本例中设定上传文件完毕后,服务端会返回给前台[0`filepath]
if (data.substring(0, 1) == 0) { //0表示上传成功(后跟上传后的文件路径),1表示失败(后跟失败描述)
$("img[id='uploadImage']").attr("src", data.substring(2));
$('#result').html("图片上传成功<br/>");
} else {
$('#result').html('图片上传失败,请重试!!');
}
},
error : function(data, status, e) { //服务器响应失败时的处理函数
$('#result').html('图片上传失败,请重试!!');
}
});
}
</script>
</head>
<body>
<div id="result"></div>
<img id="uploadImage" src="http://www.firefox.com.cn/favicon.ico">
<img id="loading" src="images/loading.gif" style="display:none;">
<input type="file" id="myBlogImage" name="myfile" />
<input type="button" value="上传图片" onclick="ajaxFileUpload()" />
</body>
</html>
输入路径http://localhost:8080/SpringMVC_04/demo/ajaxfileupload 测试即可