上传:
<pre name="code" class="java">public void saveFiles(List<MultipartFile> files) {
String savedPath = <code class="java plain"></code><code class="java string">"f:/example/test"</code>;
File path = new File(savedPath);
if (!path.exists() && !path.isDirectory()) {
path.mkdirs();//mkdirs()<span style="font-family:宋体;">可以建立多级文件夹, </span><span style="font-family:Times New Roman;">mkdir()</span><span style="font-family:宋体;">只会建立一级的文件夹</span>.<span style="color:#008b;">new</span> <span style="color:#2b91af;">File</span>(<span style="color:#8000;">"/tmp/one/two/three"</span>).mkdir();
//不会建立任何目录, 因为找不到/tmp/one/two目录,结果返回false }
for (MultipartFile file : files) {
String extName = "";
int extInd = file.getOriginalFilename().lastIndexOf(".");//表示b字符串在a字符串中最后出现的位置
if (extInd > 0) {
extName = file.getOriginalFilename().substring(extInd);
//str=str.substring(int beginIndex);截取掉str从首字母起长度为beginIndex的字符串,将剩余字符串赋值给str
}
String savedName = UUID.randomUUID().toString() + extName;
try { file.transferTo(new File(savedPath + savedName));}//转存文件 <pre name="code" class="java"> catch (IOException e) {log.info(e.getMessage());}
}
}
页面中只要使得上传文件的input的name一样就可以,然后控制器中接收一个file的List<MultipartFile> files注意页面:
<form id="form" action="add.htm" method="post" <span style="color:#FF0000;">enctype="multipart/form-data"</span>>
下载:
public static void downloadFile(File file, String fileName, HttpServletResponse response) { //File file = new File(filePath,fileName)
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (IOException ex) {
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
}
}
}
}