摘要:js提交表單(目的是做非空校驗)、上傳多文件、避免使用<button>防止表單自動提交
HTML代碼:
<form id="add_open" action="rest/admin/library/add_open" method="post" enctype="multipart/form-data">
<div class="white_title">
<span class="dangqian">公開課>></span>新增公開課
</div>
<div class="curric_form">
<div class="curric_name">
課程名稱
</div>
<div class="curric_ipt">
<input type="text" class="open_name" name="courseTitle" />
</div>
</div>
<div>
<input type="file" class="file_photo_img" id="file_img" name="file_img">
<input class="murric_file" type="file" id="courseVideoPath" name="courseVideoPath" multiple>
<input class="murric_file" type="file" id="courseVideoPath" name="courseVideoPath" multiple>
</div>
</form>
js代碼:
$(".open_save").bind("click", function()
{
//非空校驗
$("#add_open").submit();
})
Controller代碼 :
@RequestMapping(value = "/add_open", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public void addOpen(@RequestParam("courseVideoPath") MultipartFile[] courseVideoPath,HttpServletRequest request, HttpServletResponse response) throws IOException
{
...
for(int i=0; i<chapterNames.length; i++){ //循環獲取文件上傳對象
LibraryCourseHapters l=new LibraryCourseHapters();
l.setChapterName(chapterNames[i]);
l.setClassHours(chapterHourss[i]);
//上傳視頻
String saveVideoPath = request.getServletContext().getRealPath("/uploadvideo")+"/";
File file=new File(saveVideoPath);
if(!file.exists()){
file.mkdirs();
}
String videoName=courseVideoPath[i].getOriginalFilename();
String suffix=videoName.substring(videoName.lastIndexOf("."));
String newVideoName = new SimpleDateFormat("yyyyMMddHHmmssSS").format(new Date())+ UUID.randomUUID() + suffix;
if(!courseVideoPath[i].isEmpty()){
try {
FileOutputStream fos = new FileOutputStream(saveVideoPath+newVideoName);
//獲取原文件名
InputStream in=courseVideoPath[i].getInputStream();
int b = 0;
while ((b = in.read()) != -1) {
fos.write(b);
}
fos.close();
in.close();
} catch (Exception e) {
msg += "信息有誤";
e.printStackTrace();
}
}
l.setCourseVideoPath("/uploadvideo/"+newVideoName);
...
}
應用:可以實現table數據提交,在js實現數據校驗、實現複雜的業務邏輯處理