多文件上传是在单文件上传的基础上修改而来,不了解单文件上传可以参考上一篇。以下在将修改部分展示如下:
一、修改upload.html文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>多文件上传页面</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile" value="请选择文件" multiple>
<input type="submit" value="上传">
</form>
</body>
</html>
二、修改控制器:
多文件上传的逻辑与单文件类似,只是其基础上接收部分多了文件数组,再遍历一回完成如下:
package org.sang.cc;import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;import javax.servlet.http.HttpServletRequest;import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;@RestController
public class FileUploadController {SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");@PostMapping("/upload")public String upload(MultipartFile[] uploadFile,HttpServletRequest req){try {//String realPath=req.getSession().getServletContext().getRealPath("/");String realPath=ResourceUtils.getURL("classpath:").getPath(); String format=sdf.format(new Date());System.out.println("realPath:"+realPath+"static/"+format);File folder=new File(realPath+"static/"+format);if(!folder.isDirectory()){folder.mkdirs();}String[] filePath=new String[uploadFile.length];String s="";for(int i=0;i<uploadFile.length;i++){String oldName=uploadFile[i].getOriginalFilename();String newName=UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."),oldName.length());uploadFile[i].transferTo(new File(folder,newName)); filePath[i]=req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+"/static/"+format+"/"+newName; s+=filePath[i]+" <br>";} return s;}catch(IOException e){e.printStackTrace();}return "上传失败!";}
}
三、运行结果:
上传页
接收页
展示页