jsp页面:
ajax请求:
<script type="text/javascript">
$(document).ready(function () {
//选择文件事件
$("#myfile").change(function(){
$("#uploadFile").val($(this).val());
});
//上送文件
$("#executeUploadFile").click(function(){
if ($("#password").val() == "") {
new LightTip().error("请输入上送口令!");
return;
}
var files = document.getElementById("myfile").files;
if (files.length > 0) {
new Dialog().confirm('\<h6>您确定要执行上送吗?</h6>\<p>上送后,将无法撤回。</p>'
, {
buttons: [{
events: function(event) {
event.data.dialog.remove();
var files = document.getElementById("myfile").files;
var formData = new FormData();
formData.append('files', files[0]);
formData.append("password", $("#password").val());
$.ajax({
type: "post",
url: "/file/filesUpload.jhtml",
processData: false,
contentType: false,
data: formData,
success: function(data){
if (data.code > 0) {
new LightTip().success("上送成功!");
document.getElementById("myfile").value = null;
$("#uploadFile").val("");
} else {
new LightTip().error(data.msg);
}
},
error : function (data) {
new LightTip().error(data.msg);
}
});
}
}, {}]
});
} else {
new LightTip().error("请选择待上送的文件!");
}
});
});
</script>
----------
controller代码:
@Controller
@RequestMapping("/file")
public class UpLoadController {
@RequestMapping("/filesUpload")
@ResponseBody
public JSONObject filesUpload(@RequestParam MultipartFile[] files, HttpServletRequest request, String password) {
JSONObject jsonObject = new JSONObject();
//多文件上传时需要用数组
for (MultipartFile file : files) {
if (file.getSize() != 0 && password.equals("123456")) {
//得到上传文件的文件名
String filename = file.getOriginalFilename();
//得到文件真实路径
String realPath = request.getSession().getServletContext().getRealPath("") + File.separator;
//生成唯一标识,时间+文件名
String newName = realPath + filename;
File locaFile = new File(newName);
try {
file.transferTo(locaFile);
} catch (IOException e) {
e.printStackTrace();
}
jsonObject.put("code", 1);
} else {
jsonObject.put("code", 0);
}
jsonObject.put("msg", "OK");
}
return jsonObject;
}
}
springmvc配置文件:
<!-- 文件上传配置 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传的最大限制 -->
<property name="maxUploadSize" value="209715200" />
<!-- 默认编码 -->
<property name="defaultEncoding" value="UTF-8" />
<!-- 上传文件的解析 -->
<property name="resolveLazily" value="true" />
</bean>
新手上路,望多多指教……