SpringMvc + ajax 文件上传

1、依赖的jar包 【commons-io-1.4.jar】、【commons-fileupload-1.2.1.jar】

2、spring.xml 配置:

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="   
    http://www.springframework.org/schema/beans   
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
    http://www.springframework.org/schema/aop   
    http://www.springframework.org/schema/aop/spring-aop-3.1.xsd  
    http://www.springframework.org/schema/tx   
    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.1.xsd
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">




<context:annotation-config />
<context:component-scan base-package="com.richsoft.gis.controller" />
<aop:aspectj-autoproxy />


<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json</value>
</list>
</property>
</bean>


<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>

<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->  
 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
   <property name="defaultEncoding" value="UTF-8"/>  
   <!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->  
   <property name="maxUploadSize" value="200000000"/>  
    <property name="maxInMemorySize" value="40960" />  
 </bean>  
   
 <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->  
 <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->  
 <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
   <property name="exceptionMappings">  
     <props>  
       <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 -->  
       <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">404</prop>  
     </props>  
   </property>  
 </bean>



<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/page/" />
<property name="suffix" value=".jsp" />
</bean>


<mvc:interceptors>
<!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
<!-- 如果不定义 mvc:mapping path 将拦截所有的URL请求 -->
<bean class="com.richsoft.gis.security.PrivilegeInterceptor"></bean>
</mvc:interceptors>


<mvc:default-servlet-handler />

</beans>


3、jsp 代码:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="ctx" value="<%=request.getContextPath()%>" />
<!DOCTYPE html>


<html>
<head lang="en">
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"  id="ctx" basepath="${ctx}">
    <title>业务数据上传</title>
 <link href="/cmc/assets/css/vendor/upload.css" rel="stylesheet" type="text/css"/> 
 <!-- <link href="/cmc/assets/css/vendor/jquery.fileupload-ui.css" rel="stylesheet" type="text/css"/> -->


<style>
.upload_box{width:800px; margin:1em auto;}
.upload_main{border-width:1px 1px 2px; border-style:solid; border-color:#ccc #ccc #ddd; background-color:#fbfbfb;}
.upload_choose{padding:1em;}
.upload_drag_area{


display:inline-block; 
border: 2px dashed #BBB;  
padding: 25px 5px; 
text-align:center; 
font-size: 20pt;  
color: #BBB; 
        border-radius: 5px;
width:50%; 
margin-left:.5em;  
vertical-align:middle;
}


.upload_drag_hover{


border-color:#069; 
box-shadow:inset 2px 2px 4px rgba(0, 0, 0, .5); color:#333;

}




.upload_preview{border-top:1px solid #bbb; border-bottom:1px solid #bbb; background-color:#fff; overflow:hidden; _zoom:1;}
.upload_append_list{height:100px; padding:0 1em; float:left; position:relative;}
.upload_delete{margin-left:2em;}
.upload_image{max-height:250px; padding:5px;}
.upload_submit{padding-top:1em; padding-left:1em;}
.upload_submit_btn{display:none; height:32px; font-size:14px;}
.upload_loading{height:250px; background:url(null) no-repeat center;}
.upload_progress{display:none; padding:5px; border-radius:10px; color:#fff; background-color:rgba(0,0,0,.6); position:absolute; left:25px; top:45px;}
</style>
</head>


<body>


<div id="main">
    <div id="body" class="light">
    <div id="content" class="show">
            <div class="demo">
            <form id="uploadForm" action="${ctx}/datum/uploadFiles" method="post" enctype="multipart/form-data">
                    <div class="upload_box">
                        <div class="upload_main">
                            <div class="upload_choose">
                                <input  multiple="true"  id="fileImage"  type="file" size="30" name="fileselect[]" />
                                <span id="fileDragArea" class="upload_drag_area">或者将文件拖到此处</span>
                            </div>
                            <div id="preview" class="upload_preview"></div>
                        </div>
                        <div class="upload_submit">
                            <button type="button" id="fileSubmit" class="upload_submit_btn">确认上传</button>
                        </div>
                        <div id="uploadInf" class="upload_inf"></div>
                    </div>
                </form>
            </div>
        </div>       
    </div>
</div>


<script src="/cmc/assets/js/datumfile_upload.js" type="text/javascript"></script>
 <script src="/cmc/assets/js/vendor/jquery-upload.js" type="text/javascript"></script>
<script  type="text/javascript">
var params = {
fileInput: $("#fileImage").get(0),
dragDrop: $("#fileDragArea").get(0),
upButton: $("#fileSubmit").get(0),
url: $("#uploadForm").attr("action"),
filter: function(files) {
var arrFiles = [];
for (var i = 0, file; file = files[i]; i++) {
// if (file.type.indexOf("image") == 0) {
// if (file.size >= 512000) {
// alert('您这张"'+ file.name +'"图片大小过大,应小于500k');
//} else {
arrFiles.push(file);
//}
//} else {
//alert('文件"' + file.name + '"不是图片。');
//}
}
return arrFiles;
},
onSelect: function(files) {
var html = '', i = 0;
$("#preview").html('<div class="upload_loading"></div>');
var funAppendImage = function() {
file = files[i];
if (file) {
var reader = new FileReader()
reader.onload = function(e) {
html = html + '<div  id="uploadList_'+ i +'" class="upload_append_list"><p><strong>' + file.name + '</strong>'+ 
'<a href="javascript:" class="upload_delete" title="删除" data-index="'+ i +'">删除</a><br />' +
'<img id="uploadImage_' + i + '" src="' + e.target.result + '" class="upload_image" /></p>'+ 
'<span id="uploadProgress_' + i + '" class="upload_progress"></span>' +
'</div>';

i++;
funAppendImage();
}
reader.readAsDataURL(file);
} else {
$("#preview").html(html);
if (html) {
//删除方法
$(".upload_delete").click(function() {
ZXXFILE.funDeleteFile(files[parseInt($(this).attr("data-index"))]);
return false;
});
//提交按钮显示
$("#fileSubmit").show();
} else {
//提交按钮隐藏
$("#fileSubmit").hide();
}
}
};
funAppendImage();
},
onDelete: function(file) {
$("#uploadList_" + file.index).fadeOut();
},
onDragOver: function() {
$(this).addClass("upload_drag_hover");
},
onDragLeave: function() {
$(this).removeClass("upload_drag_hover");
},
onProgress: function(file, loaded, total) {
var eleProgress = $("#uploadProgress_" + file.index), percent = (loaded / total * 100).toFixed(2) + '%';
eleProgress.show().html(percent);
},
onSuccess: function(file, response) {
$("#uploadInf").append("<p>文件:" +  file.name +"上传成功!"+ "</p>");
},
onFailure: function(file) {
$("#uploadInf").append("<p>文件" + file.name + "上传失败!</p>");
$("#uploadImage_" + file.index).css("opacity", 0.2);
},
onComplete: function() {
//提交按钮隐藏
$("#fileSubmit").hide();
//file控件value置空
$("#fileImage").val("");
$("#uploadInf").append("<p>文件全部上传完毕,可继续添加上传。</p>");
}
};
ZXXFILE = $.extend(ZXXFILE, params);
ZXXFILE.init();
</script>
</body>
</html>


4、js、css

/**
 * 支持可选择,可拖拽批量上传文件插件
 * @type 
 */


var ZXXFILE = {
fileInput: null,
dragDrop: null,
upButton: null,
url: "",     //上传控制层路径
fileFilter: [], // 过滤后的文件名称
filter: function(files) {
return files;
},
onSelect: function() {},
onDelete: function() {},
onDragOver: function() {},
onDragLeave: function() {},
onProgress: function() {},
onSuccess: function() {}, //上传成功回调函数
onFailure: function() {},
onComplete: function() {},



funDragHover: function(e) {
e.stopPropagation();
e.preventDefault();
this[e.type === "dragover"? "onDragOver": "onDragLeave"].call(e.target);
return this;
},

funGetFiles: function(e) {

this.funDragHover(e);


var files = e.target.files || e.dataTransfer.files;

this.fileFilter = this.fileFilter.concat(this.filter(files));
this.funDealFiles();
return this;
},


funDealFiles: function() {
for (var i = 0, file; file = this.fileFilter[i]; i++) {

file.index = i;
}

this.onSelect(this.fileFilter);
return this;
},


funDeleteFile: function(fileDelete) {
var arrFile = [];
for (var i = 0, file; file = this.fileFilter[i]; i++) {
if (file != fileDelete) {
arrFile.push(file);
} else {
this.onDelete(fileDelete);
}
}
this.fileFilter = arrFile;
return this;
},


funUploadFile: function() {
var self = this;
if (location.host.indexOf("sitepointstatic") >= 0) {

return;
}
for (var i = 0, file; file = this.fileFilter[i]; i++) {
(function(file) {
var xhr = new XMLHttpRequest();
var formData = new FormData();
if (xhr.upload) {

xhr.upload.addEventListener("progress", function(e) {
self.onProgress(file, e.loaded, e.total);
}, false);


xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
self.onSuccess(file, xhr.responseText);
self.funDeleteFile(file);
if (!self.fileFilter.length) {

self.onComplete();
}
} else {
self.onFailure(file, xhr.responseText);
}
}
};


xhr.open("POST", self.url, true);
formData.append('myfile',file);
xhr.send(formData);

// xhr.setRequestHeader("X_FILENAME", file.name);
// xhr.send(file);
}
})(file);
}

},

init: function() {
var self = this;

if (this.dragDrop) {
this.dragDrop.addEventListener("dragover", function(e) { self.funDragHover(e); }, false);
this.dragDrop.addEventListener("dragleave", function(e) { self.funDragHover(e); }, false);
this.dragDrop.addEventListener("drop", function(e) { self.funGetFiles(e); }, false);
}


if (this.fileInput) {
this.fileInput.addEventListener("change", function(e) { self.funGetFiles(e); }, false);
}


if (this.upButton) {
this.upButton.addEventListener("click", function(e) { self.funUploadFile(e); }, false);

}
};


css部分:






body {
    background: none repeat scroll 0 0 #a0b3d6;
    color: #333;
    font-family: Arial,sans-serif;
    font-size: 84%;
    line-height: 1.5;
    margin: 0;
}
a {
    color: #34538b;
    text-decoration: none;
}
a:hover {
    text-decoration: underline;
}
a img {
    border: 0 none;
}
input, select, textarea {
    font-size: 100%;
}
#header {
    height: 60px;
    padding: 0 0 0 40px;
}
#header .logo {
    float: left;
    margin-top: 12px;
    overflow: hidden;
}
#main {
    background: none repeat scroll 0 0 #beceeb;
    overflow: hidden;
    width: 100%;
}
#main h1 {
    background: none repeat scroll 0 0 #c1d5eb;
    font-family: "kaiti","microsoft yahei";
    font-size: 1.3em;
    line-height: 40px;
    margin: 0;
    text-align: center;
    text-shadow: 0 1px 0 #f2f2f2;
}
#body {
    overflow: hidden;
    padding: 0;
}
#body .part {
    background: none repeat scroll 0 0 white;
    min-height: 500px;
    width: 50%;
}
#code {
    float: left;
    margin-bottom: -999em;
    margin-left: -1px;
    padding-bottom: 999em;
}
#effect {
    float: right;
    margin-bottom: -999em;
    margin-right: -1px;
    padding-bottom: 999em;
}
#body h3 {
    background: none repeat scroll 0 0 #f0f3f9;
    border-bottom: 1px solid #ededed;
    color: #4e4e4e;
    font-size: 1.1em;
    line-height: 30px;
    margin: 0;
    padding-left: 10px;
    text-shadow: 0 1px 0 white;
}
#footer {
    border-top: 1px solid #486aaa;
    font-family: "Lucida Grande",Verdana,sans-serif;
    line-height: 1.3;
    padding: 15px 0;
    text-align: center;
    text-shadow: 1px 1px #cad5eb;
}
#footer::before {
    background-color: #909baf;
    color: #aaa;
    content: "";
    display: block;
    height: 1px;
    overflow: hidden;
    position: relative;
    top: -15px;
}
#footer img {
    margin-bottom: -3px;
}
.show {
    padding-bottom: 20px;
}
.show h5 {
    border-bottom: 1px dotted #e5e5e5;
    font-size: 0.9em;
    line-height: 20px;
    margin: 0 0 0 8px;
    padding: 10px 0 2px 2px;
}
.demo {
    padding: 10px;
}
.demo::after {
    clear: both;
    content: "";
    display: table;
}
pre {
    font-family: "simsun";
}
#ad, .ad {
    color: #fff;
    height: 60px;
    margin: 0 auto;
    width: 468px;
}
.ad {
    background-color: rgba(0, 0, 0, 0.35);
    font-size: 12px;
    position: absolute;
    right: 0;
    text-align: center;
    top: 0;
}
@media screen and (max-width: 468px) {
#ad {
    display: none;
}
}
@media screen and (max-width: 700px) {
.ad {
    display: none;
}
}
.light {
    background: none repeat scroll 0 0 #f0f3f9;
}
#content {
    -moz-border-bottom-colors: none;
    -moz-border-left-colors: none;
    -moz-border-right-colors: none;
    -moz-border-top-colors: none;
    background: none repeat scroll 0 0 white;
    border-color: #cad5eb;
    border-image: none;
    border-style: solid;
    border-width: 0 2px;
    font-family: "Lucida Grande",Verdana;
    min-height: 500px;
}
.article {
    clear: both;
    font-family: Arial;
    font-size: 0.86em;
    padding: 10px 0;
}
.article_new {
    clear: both;
    font-family: Arial;
    font-size: 0.86em;
    line-height: 20px;
    margin: -31px 10px 0 0;
    padding: 5px 0;
    text-align: right;
}
#back {
    margin-top: -25px;
    position: absolute;
    right: 10px;
}


action 部分

/**
* 多文件文件上传

* @param file
* @param request
* @return
* @throws IOException
*/
@RequestMapping("/uploadFiles")
public @ResponseBody
boolean uploadFiles(@RequestParam("myfile") CommonsMultipartFile[] files,
HttpServletRequest request) throws IOException {


// 判断file数组不能为空并且长度大于0
if (files != null && files.length > 0) {
// 循环获取file数组中得文件
for (int i = 0; i < files.length; i++) {
CommonsMultipartFile file = files[i];
// 保存文件
saveFile(file, request);
}
}
return true;
}


/***
* 保存文件

* @param file
* @return
*/
private boolean saveFile(MultipartFile file, HttpServletRequest request) {
// 判断文件是否为空
if (!file.isEmpty()) {
try {
// 文件保存路径
String filePath = request.getSession().getServletContext()
.getRealPath("/")
+ "upload\\" + file.getOriginalFilename();


File f = new File(filePath);
if (!f.exists()) {
f.mkdirs();
}


// 转存文件
file.transferTo(new File(filePath));


// 保存数据到数据库
String strType = "";
String name = file.getOriginalFilename();
int num = name.indexOf(".");
strType = name.substring(num, name.length());


MapSource mapInfo = new MapSource();
mapInfo.setUri(filePath);
mapInfo.setTitle(name);
mapInfo.setSummary(name);
mapInfo.setType(strType);
// mapInfo.setCruserId(100);
// mapInfo.setCrtime(new Date());


mapSourceService.save(mapInfo);


return true;
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值