在項目中,經常用到的一個功能就是文件的上傳和下載,不過大多數情況下都是通用的工具類,自己寫的情況較少,這裡寫個通過Spring框架和ajaxFileUpload插件實現上傳的小功能,做個練習和記錄。
首先配置下SpringMVC的配置文件,配置支持文件上傳
<!-- 配置MultipartResolver 用於文件上傳 使用spring的CommosMultipartResolver
說明:
p:defaultEncoding="UTF-8":這裡設置默認的文件編碼為UTF-8,必須與用戶JSP的默認編碼一致;
p:maxUploadSize="5000000":指定文件上傳大小,單位為字節;
p:uploadTempDir="fileUpload/temp":文件上傳臨時目錄,上傳完成後,就會將臨時文件刪除;
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8"
p:maxUploadSize="5000000"
p:uploadTempDir="fileUpload/temp"
>
</bean> 然後寫個簡單的JSP頁面,為了方便綁定數據,引入Spring自帶的Form表單標籤,引入語句
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %> Form表單實現一個簡單的註冊功能,雖然說美感不好,這裡還是引用了下bootstrap做了個簡單的排版。因為原版的file標籤的格式無法調整,所有用了其他的小標籤代替,然後用按鈕去觸發file標籤
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
request.setAttribute("_path", path);
%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.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">
-->
<link rel="stylesheet" href="<%=basePath%>static/css/bootstrap.css"/>
<script type="text/javascript" src="<%=basePath%>static/js/jquery.min.js"></script>
<script type="text/javascript" src="<%=basePath%>static/js/ajaxfileupload.js"></script>
<script type="text/javascript" src="<%=basePath%>static/js/bootstrap.js"></script>
<script type="text/javascript" src="<%=basePath%>static/js/jquery.json-2.4.js" charset="UTF-8"></script>
<script type="text/javascript">
var path = "${_path}";
$(function(){
/* 重置Form表單功能 */
$("#clean").click(function(){
document.getElementById("user").reset();
$("#userName").attr("value","");
$("#password").attr("value","");
$("#name").attr("value","");
$("#sex").attr("value","");
$("#file").attr("value","");
});
/* begin 附件上功能 */
$("#choose").click(function(){
$("#fileUpload").click();
});
$("#fileUpload").change(function(){
$("#file").attr("value",$("#fileUpload").val());
$.ajaxFileUpload({
type: "POST",
url: path+"/fileUpload.do",
data:{fileName:$("#fileUpload").val()},//要傳到後台的參數,沒有可以不寫
secureuri : false,//是否啟用安全提交,默認為false
fileElementId:'fileUpload',//文件選擇框的id屬性
dataType: 'json',//服務器返回的格式
async : false,
success: function(mes){
if(mes.message=="OK"){
alert("附件上傳成功");
}
if(mes.message=="NG"){
alert("附件上傳失敗");
}
},
error: function (){
alert("附件上傳失敗");
}
});
});
/* end 附件上功能 */
});
</script>
</head>
<body>
<div class="container" style="width: 100%" >
<div> </div>
<div class="row">
<div class="col-lg-5 col-md-5 col-sm-5 col-xs-5"></div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1" >註冊頁面</div>
</div>
<div> </div>
<div class="row">
<form:form commandName="user" action="${_path }/register.do" method="post" enctype="multipart/form-data">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4"></div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1" style="text-align:right">賬號:</div>
<form:input path="userName" type = "text" value = "" class="input-large"/>
<div> </div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4"></div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1" style="text-align:right">密碼:</div>
<form:input path="password" type = "password" class="input-large"/>
<div> </div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4"></div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1" style="text-align:right">姓名:</div>
<form:input path="name" type = "text" value = "" class="input-large"/>
<div> </div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4"></div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1" style="text-align:right">性別:</div>
<form:input path="sex" type = "text" value = "" class="input-large"/>
<div> </div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4"></div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1" style="text-align:right">附件:</div>
<input id = "fileUpload" name = "fileUpload" type = "file" style=" display: none">
<form:input type ="text" class="input-large" path= "file" />
<input id ="choose" type="button" value = "選擇" class="btn btn-primary btn-xs"/>
<div> </div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4"></div>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-2" style="text-align:right">
<input id = "upload" type = "submit" value = "提交" class="btn btn-default btn-sm"/>
<input id ="clean" type="button" value = "清除" class="btn btn-default btn-sm"/>
</div>
</form:form>
</div>
</div>
</body>
</html>
後台頁面控制器,因為用了SpringMVC的form表單,所以在渲染的時候模型中一定要有user這個對象,所以我們用控制器跳轉頁面
@RequestMapping("/Login.do")
public String Login(@ModelAttribute("user") User user, Model model){
System.out.println("進入");
user.setName("小明");
user.setSex("男");
user.setUserName("葉良辰");
model.addAttribute("user", user);
return "index";
}這裡為了顯示SpringMVC form的自動綁定功能,我給user對象設置了值,在JSP頁面,如果form:input標籤由path屬性和user里的屬性一樣,會自動設置值

附件的js代碼在上面的JSP頁面中已經寫好了,下面是後台控制的controller,因為我們配置了multipartResolver,所以form表單是設置了enctype=”multipart/form-data,後台一樣能直接取出文本值
接受文本框內容的controller
@RequestMapping("/register.do")
public String register(@ModelAttribute("user") User user, Model model){
model.addAttribute("user", user);
System.out.println(user);
return "index";
}附件上傳的controller
@RequestMapping("/fileUpload.do")
public @ResponseBody Message fileUpload(HttpServletRequest request,@RequestParam("fileUpload") MultipartFile file,
@RequestParam("fileName") String fileName,@ModelAttribute("user") User user,Model model,Message mes){
//簡單判斷文件是否為空
if(!file.isEmpty()){
try {
// 文件保存路徑
String filePath = request.getSession().getServletContext().getRealPath("/") + "fileUpload/"
+ file.getOriginalFilename();
file.transferTo(new File(filePath));
mes.setMessage("OK");
} catch (Exception e) {
mes.setMessage("NG");
e.printStackTrace();
}
}
user.setFile(fileName);
System.out.println(fileName);
model.addAttribute("user", user);
System.out.println(user);
return mes;
}原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/224029.html
微信掃一掃
支付寶掃一掃