springmvc+mybatis+oracle采用xmlhttprequest方式多文件上传与批量保存
程序员文章站
2022-06-10 17:25:45
...
我有一个【模板发布】页面,代码,预览图如下
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="<%=request.getContextPath()+"/resources/js/jquery-1.7.1.js"%>"></script> <script type="text/javascript" src="<%=request.getContextPath()+"/resources/js/uploadPanel.js"%>"></script> <title>发布模板</title> </head> <body> <form action="<%=request.getContextPath()+"/faceController/insert" %>" method="post" enctype="multipart/form-data"> <table> <tr> <td><input id="face_submit" type="submit" value="发布" /></td> </tr> <tr> <td>标题:</td> <td><input type="text" name="title" value=""/></td> </tr> <tr> <td>描述:</td> <td><textarea rows="10" cols="50" name="message"></textarea></td> </tr> <tr> <td><input type="hidden" name="fileIds" value=""></td> </tr> </table> </form> <input type="button" name="checkButton" value="选择文件" onclick="clickButton()" style="cursor:pointer;"/> <form id="upload_panel_form" action="<%=request.getContextPath()+"/fileController/upload" %>" method="post" enctype="multipart/form-data"> <input id="checkFile" class="checkFile" type="file" style="display: none;" name="files" accept=".zip,.jpg,.jpeg" value="选择文件" onchange="changeList()" multiple="multiple"/> </form> <div id="upload_panel_list_div" class="upload_panel_list_div"> <table id="upload_panel_list_table" class="upload_panel_list_table"> <tbody id="upload_panel_list_table_tbody" class="upload_panel_list_table_tbody"> <tr> </tr> </tbody> </table> </div> </body> </html>
function clickButton(){ $(".checkFile").click(); } var xhr; function changeList(){ var fd = new FormData(); var files = document.getElementById('checkFile').files; if(files.length == 0){ alert("请选择需要上传的文件"); return; } var tbody = $("#upload_panel_list_table_tbody"); for (var i = 0; i < files.length; i++) { var file = files[i]; var fileSize = file.size; var fileName = file.name; var fileType = fileName.split('.')[fileName.split('.').length-1]; var td = ''; if(fileType == 'jpg'){ td = "<td class='upload_panel_table_td_width1'><img class='temp-uploading-img' alt='' src='/service/resources/image/loding-image.gif' width='100px'></td>"; var tr = $('#upload_panel_list_table_tbody tr:last'); tr.append(td); if(tr.children('td').length == 3){ tbody.append("<tr></tr>"); } fd.append("files", files[i]); } } $("#face_submit").attr("disabled","disabled"); xhr = new XMLHttpRequest(); xhr.open("POST", document.getElementById('upload_panel_form').action); xhr.onreadystatechange = callback; xhr.send(fd); } function callback(){ if(xhr.readyState == 4){ if (xhr.responseText != null && xhr.responseText != ''){ $("#checkFile").value = ""; var result = xhr.responseText; //此处需转换。 var json = eval("(" + result + ")").fileList; // filePath // alert($(".temp-uploading-img").length); var files = $("input[name='fileIds']"); var files_val = files.val(); for (var int = 0; int < json.length; int++) { var fileJson = json[int]; var img = $(".temp-uploading-img").eq(0); img.attr("src",fileJson.filePath); img.removeClass(); files_val += files_val == '' ? fileJson.id : ("~" + fileJson.id); } $("#face_submit").removeAttr("disabled"); files.val(files_val); } } }
此处,我选择图片后,会先将图片上传到服务器,然后在页面记录图片上传后返回的id。
需要注意的是,我此处的上传路径,也就是realPath,并不是与在该项目中的,而是我自己建立的一个文件服务器。如果需要再本项目中,你可以在realPath前加入request.getContextPath()等项目路径。
下面是文件上传的java代码:
@RequestMapping("upload") public void uploadFaceImage(HttpServletRequest request,HttpServletResponse response,ModelAndView modelAndView,RedirectAttributes attr,@RequestParam MultipartFile[] files,Face face) throws IOException{ Calendar calendar = Calendar.getInstance(); User user = (User) request.getSession().getAttribute(WebKeys.USERKEY); String realPath = "/" + "uploadfile" + "/" + user.getUserId() + "/" + calendar.get(Calendar.YEAR) + "_" + (calendar.get(Calendar.MONTH) + 1) + "_" + calendar.get(Calendar.DAY_OF_MONTH); File temp = new File(realPath); if(!temp.exists()){ temp.mkdirs(); } List<com.face.model.File> fileList = new ArrayList<com.face.model.File>(); for (MultipartFile multipartFile : files) { if(multipartFile.isEmpty()){ System.err.println("-----------上传失败---------------"); }else{ com.face.model.File file = new com.face.model.File(); String fileName = System.currentTimeMillis() + "_" + Math.round(new Random().nextDouble() * 100000) + multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".")); file.setFileName(fileName); file.setFileOldName(multipartFile.getOriginalFilename()); file.setFileSize(BigDecimal.valueOf(multipartFile.getSize())); file.setFileType(multipartFile.getContentType()); file.setFilePath(realPath + "/" + file.getFileName()); file.setUploadUserId(user.getId()); file.setCreateTime(new Date()); file.setId(fileService.getSequence()); FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), new File(realPath,file.getFileName())); fileList.add(file); } } Map<String,Object> data = new HashMap<String,Object>(); if(fileList.size() > 0){ int result = fileService.inserFileBatch(fileList); if(result > 0) data.put("fileList",fileList); } response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); String json = JSON.toJSONStringWithDateFormat(data, "YYYY-MM-dd HH-mm-ss"); System.out.println(json); PrintWriter out = null; try { out = response.getWriter(); out.append(json); } catch (IOException e) { e.printStackTrace(); }finally{ out.close(); } }
因为使用的是oracle,所以批量保存这里稍稍麻烦了一点。
我是先查出id号,然后写入File实体的id字段,然后再进行批量保存的。
下面是我的mapper:
<select id="getSequence" resultType="java.math.BigDecimal"> SELECT SEQ_T_FILE.nextval as ID from dual </select> <insert id="insertFileBatch" parameterType="java.util.List"> insert into T_FILE select A.* from( <foreach collection="list" item="item" index="index" separator="UNION"> SELECT #{item.id}, #{item.fileSize}, #{item.fileOldName}, #{item.fileName}, sysdate, #{item.uploadUserId}, #{item.filePath}, #{item.fileType} from dual </foreach> ) A </insert>
当然,如果你不需要记录文件上传后保存到数据库的id的话,就可以不用这么麻烦,可以如下方式,直接批量保存:
<insert id="insertFileBatch" parameterType="java.util.List"> insert into T_FILE select SEQ_T_FILE.nextval,A.* from( <foreach collection="list" item="item" index="index" separator="UNION"> SELECT #{item.fileSize}, #{item.fileOldName}, #{item.fileName}, sysdate, #{item.uploadUserId}, #{item.filePath}, #{item.fileType} from dual </foreach> ) A </insert>
此处要注意,所有#字段的先后顺序是以数据库中的先后顺序来排序的,如果与数据库默认的不对应,就会报错。
上一篇: php dompdf 使用
下一篇: php实现文件下载简单示例_PHP教程