SSM檔案批量上傳
阿新 • • 發佈:2019-01-11
首先我們需要在SSM框架的配置檔案中,配置一個批量上傳的元件bean
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"></property> <!-- 配置檔案的最大上傳容量限制 --> <property name="maxUploadSize" value="50242440"></property> </bean>
其次編寫一個簡單的jsp頁面來進行檔案上傳操作
<input type="file" multiple="multiple" name="files" width="120px" >
multiple="multiple" 屬性是配置可以選擇多個檔案,否則只能選擇單個檔案
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>檔案上傳下載</title> </head> <body> <form action="${pageContext.request.contextPath }/file/upload.html" method="post" enctype="multipart/form-data"> 選擇檔案:<input type="file" multiple="multiple" name="files" width="120px" > <input type="submit" value="上傳"> </form> </body> </html>
接下來我們需要編寫一個Controller類來實現檔案的批量上傳
/*** * 檔案的批量上傳 * @param files * @param request * @return * @throws Exception * @throws IOException */ @RequestMapping(value="/file/upload.html",method=RequestMethod.POST) public String upload(@RequestParam("files") MultipartFile[] files,MultipartHttpServletRequest request) throws Exception, IOException{ //獲取資料夾的名字 List<String[]> filess=new ArrayList<String[]>(); String path = request.getSession().getServletContext().getRealPath("/upload"); StringBuffer stringbuffer=new StringBuffer(); //對傳進來的檔案陣列,進行 迴圈複製 for(MultipartFile multipartFile:files){ //判斷檔案是否為空 if(!multipartFile.isEmpty()) { //將多個檔名拼接在一個字串中,用;分隔 stringbuffer.append(multipartFile.getOriginalFilename()); stringbuffer.append(";"); File dir=new File(path, multipartFile.getOriginalFilename()); //將檔名和對應的路徑存放在陣列中 String[] files1={multipartFile.getOriginalFilename(),dir.toPath().toString()}; //將一個檔案的標識資訊存入集合中 filess.add(files1); //System.out.println(dir.toPath()); //檔案不存則在建立 if(!dir.exists()&&!dir.isDirectory()){ dir.mkdirs(); } //檔案進行復制 multipartFile.transferTo(dir); } } String s=stringbuffer.substring(0, stringbuffer.length()-1); //將檔案資訊集合存入資料庫中 fileOperateService.insertfiles(filess); //跳轉到呼叫檔案顯示的介面 return "redirect:/file/showall.html"; }
以上便為實現檔案批量上傳的全部程式碼,如果不需要存入資料庫,然後查詢出來的顯示到前臺,可以將其中部分程式碼刪除