1、Form表单,enctype文件类型,
<form class="form-horizontal" action="/MyRen/resultmanage/uploadexcel" method="post" id="form1"
enctype="multipart/form-data" target="hidden_frame">
<input name="files" type="file" class="form-control" placeholder=""
style="padding: 0.2em 0.5em;" accept=".xls,.xlsx,.doc,.pdf">
<iframe id="hidden_frame" name="hidden_frame" style="display:none"></iframe>
因为form表单提交后总是会刷新界面,所以target可以实现刷新后的界面仍然是本界面。 input通过 accept属性限制文件类型。
2、ajax法。
new AjaxUpload('#upload', {
action: baseURL + "registerathlete/uploadexcel",
name: 'file',
autoSubmit:true,
responseType:"json",
onSubmit:function(file, extension){
if (!(extension && /^(xls|xlsx)$/.test(extension.toLowerCase()))){
alert('只支持xls、xlsx格式的表格!');
return false;
}
},
后台处理
@RequestMapping("/uploadexcel")
public void uploadExcel(
@RequestParam("result_id") String result_id,
@RequestParam("competition_id") String competition_id,
@RequestParam("additional_word") String additional_word,
@RequestParam(value = "files", required = false) MultipartFile file,
ModelMap model, HttpServletRequest request,
HttpServletResponse response) throws Exception, IOException {
// String path =
// request.getSession().getServletContext().getRealPath("/download/GradeDownLoad");
String path = Config.FILE_RESULT_UPLOAD_PATH;
String fileName = UUID.randomUUID() + "-" + file.getOriginalFilename();
File targetFile = new File(path, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
System.out.println(path + "--" + fileName);
// 本地测试
file.transferTo(targetFile);