stringMVC_09檔案批量上傳
阿新 • • 發佈:2018-12-24
一.思路
在檔案上傳的基礎上引入陣列可以實現批量上傳,只需要更改一下前段頁面和controller類即可
檔案上傳: https://www.cnblogs.com/aihuadung/p/10167507.html
二.實現
在檔案上傳的基礎上更改fileupload.jsp
<form action="batchupload.do" method="post" enctype="multipart/form-data"> 檔案上傳:<input type="file" name="file" value="選擇檔案"/><br/> 檔案上傳:<input type="file" name="file" value="選擇檔案"/><br/> <input type="submit" value="submit"/> </form>
建立HelloController類
package com.ahd.controller; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException;import java.io.InputStream; import java.io.OutputStream; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.commons.CommonsMultipartFile; @Controller public class HelloController5{ @RequestMapping("/batchupload") public String upload(@RequestParam("file")CommonsMultipartFile []files,HttpServletRequest req,ModelMap mm) throws IOException{ //獲取上傳路徑 String path=req.getRealPath("upload"); InputStream is=null; OutputStream os=null; for(CommonsMultipartFile file:files){ //獲取檔名稱 String filename=file.getOriginalFilename(); is = file.getInputStream(); os = new FileOutputStream(new File(path,filename)); byte[]b=new byte[1024]; int len=0; while((len=is.read(b))!=-1){ os.write(b, 0, len); } } is.close(); os.close(); mm.addAttribute("msg", "檔案上傳成功"); return "success"; } }