0、jar包(链接:https://pan.baidu.com/s/1MdAHnKoc5-r3jY58Vwz-1Q 密码:kdvh)
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
等其他springmvc需要的jar
1、js(链接:https://pan.baidu.com/s/1PraViPr8Y_SdNI0bUYlitA 密码:lp5y)
jquery-1.11.1.min.js
jquery.form.js
2、上传的工具包
package com.ws.util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
public class FileUpload {
/**
* @param file //文件对象
* @param filePath //上传路径
* @param fileName //文件名
* @return 文件名
*/
public static String fileUp(MultipartFile file, String filePath, String fileName){
String extName = ""; // 扩展名格式:
try {
if (file.getOriginalFilename().lastIndexOf(".") >= 0){
extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
}
copyFile(file.getInputStream(), filePath, fileName+extName).replaceAll("-", "");
} catch (IOException e) {
System.out.println(e);
}
return fileName+extName;
}
/**
* 写文件到当前目录的upload目录中
* 没用到这个...
* @param in
* @param fileName
* @throws IOException
*/
private static String copyFile(InputStream in, String dir, String realName)
throws IOException {
File file = new File(dir, realName);
if (!file.exists()) {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
FileUtils.copyInputStreamToFile(in, file);
return realName;
}
}
3、控制层
package com.ws;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.ws.util.FileUpload;
@Controller
public class TestController {
@RequestMapping(value = "/toAdd")
public ModelAndView toAdd() {
ModelAndView mv = new ModelAndView();
mv.setViewName("test/edit");
return mv;
}
@RequestMapping(value = "/save")
public ModelAndView save(HttpServletRequest request) {
ModelAndView mv = new ModelAndView();
Integer zj_count = Integer.parseInt(request.getParameter("zj_count"));
for (int i = 1; i <= zj_count; i++) {
System.out.println(request.getParameter("zj" + i));
// 获取每个章节有几个课时
Integer zj_ks_count = Integer.parseInt(request.getParameter("ks" + i + "_count"));
for (int j = 1; j <= zj_ks_count; j++) {
System.out.println("\t" + request.getParameter("zj" + i + "_ks" + j) + "\t" + request.getParameter("file_path_zj" + i + "_ks" + j));
}
}
mv.setViewName("redirect:toAdd.do");
return mv;
}
// 上传文件的目录(自己改啊!!)
static final String filePath = "G:\\shenmeshenme\\apache-tomcat-7.0.26\\webapps\\springMVCFreeMarker\\static\\uploadFiles";
/**
* 异步上传文件
* @param file
* @param request
* @param out
*/
@RequestMapping(value = "/uploadFile")
public void uploadFile(@RequestParam MultipartFile file, HttpServletRequest request, PrintWriter out){
try {
String newFileName = FileUpload.fileUp(file, filePath, new Date().getTime()+"");
out.print(newFileName);
} catch (Exception e) {
e.printStackTrace();
out.print("error");
} finally {
out.close();
out.flush();
}
}
}
4、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>新增</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">
-->
<style type="text/css">
.zj_div{
background: #ddf;
}
.ks_div{
background: #dff;
margin-left: 50px;
}
input[readonly='readonly']{
cursor: pointer;
}
</style>
</head>
<body>
<form action="save" method="post">
<input type="button" value="添加章节" onclick="addZj()">
<div id="all">
<div id="div_zj1">
<div class="zj_div">
<input name="zj1" value="章节1">
<input type="button" value="添加课时" onclick="addKs(1)">
<!-- 这个章节有几个课时 -->
<input type="hidden" name="ks1_count" id="ks1_count" value="1">
</div>
<div class="ks_div">
<input name="zj1_ks1" value="章节1的课时1">
<input type="text" name="file_path_zj1_ks1" id="file_path_zj1_ks1" onclick="chooseFile('file_path_zj1_ks1')" readonly="readonly" placeholder="点我选择文件">
<br>
</div>
</div>
</div>
<!-- 共有几个章节 -->
<input type="hidden" value="1" name="zj_count" id="zj_count">
<br>
<input type="button" value="保存" onclick="save()">
</form>
<form action="uploadFile.do" id="uploadFileForm" method="post" enctype="multipart/form-data" style="display: none;">
<input type="file" name="file" id="file" onchange="fileChange()">
</form>
<script type="text/javascript" src="static/js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="static/js/jquery.form.js"></script>
<script type="text/javascript">
// 章节的序号
var zjXuHao = 1;
// 添加章节
function addZj(){
zjXuHao++;
var htmls ="<div id=\"div_zj"+zjXuHao+"\">"+
"<div class=\"zj_div\">"+
"<input name=\"zj"+zjXuHao+"\" value=\"章节"+zjXuHao+"\">"+
"<input type=\"button\" value=\"添加课时\" onclick=\"addKs("+zjXuHao+")\">"+
"<input type=\"hidden\" name=\"ks"+zjXuHao+"_count\" id=\"ks"+zjXuHao+"_count\" value=\"0\">"+
"</div>"+
"</div>";
$("#all").append(htmls);
// 共几个章节
$("#zj_count").val(zjXuHao);
}
// 添加课时
var ksXuHao = 1;
function addKs(i){
var ksCount = parseInt($("#ks"+i+"_count").val())+1;
var htmls = "<div class=\"ks_div\">"+
"<input name=\"zj"+i+"_ks"+ksCount+"\" value=\"章节"+i+"的课时"+ksCount+"\">\n"+
"<input type=\"text\" name=\"file_path_zj"+i+"_ks"+ksCount+"\" id=\"file_path_zj"+i+"_ks"+ksCount+"\" onclick=\"chooseFile('file_path_zj"+i+"_ks"+ksCount+"')\" readonly=\"readonly\" placeholder=\"点我选择文件\">"+
"<br>"+
"</div>";
$("#div_zj"+i).append(htmls);
$("#ks"+i+"_count").val(ksCount);
}
function save(){
$("form")[0].submit();
}
//var zjArr = [1];
// zjArr.push();//给数组里面添加元素
// 选择文件
function chooseFile(filePathId){
$("#file").attr("filepathid", filePathId);
$("#file").click();
}
var fileMaxSize = 5*1024*1024;
// 选择文件后,准备上传
function fileChange(){
var fileSize = 0;
var ua = window.navigator.userAgent;
if (ua.indexOf("MSIE")>=1){//ie旧版浏览器
var fileobject = new ActiveXObject ("Scripting.FileSystemObject");//获取上传文件的对象
var file = fileobject.GetFile(document.getElementById("file").value);//获取上传的文件
fileSize = file.Size;
} else {//其它浏览器
fileSize = $("#file")[0].files[0].size;
}
if (fileSize <= 0) {
alert("文件错误~");
$("#file").removeAttr("filepathid");
return;
}
if (fileSize > fileMaxSize) {
alert("文件不能超过5M~");
$("#file").removeAttr("filepathid");
return;
}
var filePathId = $("#file").attr("filepathid");
if (filePathId != null && filePathId != '') {
uploadPic(filePathId);
}
}
// 上传文件
function uploadPic(id) {
// 上传设置
var options = {
// 规定把请求发送到那个URL
url : "uploadFile.do",
// 请求方式
type : "post",
// 服务器响应的数据类型
dataType : "text",
// 请求成功时执行的回调函数
success : function(data, status, xhr) {
// 图片显示地址
if (data != 'error' && data != null && data != '') {
$("#" + id).val(data);
} else {
alert("上传失败,请重试!");
}
}
};
$("#uploadFileForm").ajaxSubmit(options);
}
</script>
</body>
</html>
5、spring-mvc.xml配置
<!-- 设置上传文件最大值 100M=100*1024*1024(B)=1048576 bytes -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600" />
</bean>