各种配置文件已经在上一篇博文中说过了,这次实例就直接贴文件上传的方法了.
多文件上传案例(单文件上传去掉循环即可)
@RequestMapping("/uploads.do")
public String uploads(@RequestParam(value="file",required=false)MultipartFile[] files,HttpServletRequest request){
for (MultipartFile file : files) {
//要保存的地址,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全
String savePath=request.getServletContext().getRealPath("/WEB-INF/upload");
//如果没有保存文件的目录,就创建该目录
File saveDir=new File(savePath);
if(!saveDir.exists() && !saveDir.isDirectory()){
saveDir.mkdir();
}
//获取上传文件的名称
String uploadFileName=file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf('.'));
//获取上传文件的扩展名
String fileExtName=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
//设置上传后文件的名称,UUID保证上传文件名唯一
String saveFilename=uploadFileName+"_"+UUID.randomUUID()+fileExtName;
//得到文件的保存目录
String realSavePath = makePath(saveFilename, savePath);
//打印保存地址,方便上传文件后查看
System.out.println(realSavePath);
//要被输入的文件
File targetFile=new File(realSavePath,saveFilename);
try{
//将文件保存在目录
file.transferTo(targetFile);
}catch(Exception e){
e.printStackTrace();
}
}
request.setAttribute("message", "文件上传成功!");
return "result";
}
//为防止一个目录下面出现太多文件,要使用hash算法打散存储
private String makePath(String filename,String savePath){
//得到文件名的hashCode的值,得到的就是filename这个字符串对象在内存中的地址
int hashcode = filename.hashCode();
int dir1 = hashcode&0xf; //0--15
int dir2 = (hashcode&0xf0)>>4; //0-15
//构造新的保存目录
String dir = savePath + "\\" + dir1 + "\\" + dir2; //upload\2\3 upload\3\5
//File既可以代表文件也可以代表目录
File file = new File(dir);
//如果目录不存在
if(!file.exists()){
//创建目录
file.mkdirs();
}
return dir;
}
文件下载
@RequestMapping("/download.do")
public ResponseEntity<byte[]> download(HttpServletRequest request,String filename) throws IOException{
//下载文件路径
String path = request.getServletContext().getRealPath("/images/");
File file = new File(path + File.separator + filename);
HttpHeaders headers = new HttpHeaders();
//下载显示的文件名,解决中文名称乱码问题
String downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
//通知浏览器以attachment(下载方式)打开图片
headers.setContentDispositionFormData("attachment", downloadFielName);
//application/octet-stream : 二进制流数据(最常见的文件下载)。
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED);
}
第二种文件下载
package cn.dyw.generatesql.utils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
public class DownloadUtil {
public static String encoding = "UTF-8";
/**
* 下载
* @param request
* @param response
* @throws Exception
*/
public static void downLoad(String path,HttpServletRequest request,HttpServletResponse response) throws Exception{
File file = new File(path);
if( file.exists() ){
String fileName = file.getName();
String userAgent = request.getHeader("User-Agent");
//针对IE或者以IE为内核的浏览器:
if (userAgent.contains("MSIE")||userAgent.contains("Trident")) {
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
}
else {
//非IE浏览器的处理:
fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
}
response.setHeader("Content-Disposition", "attachment;filename=" + fileName );
response.setContentType("application/OCTET-STREAM;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
try {
FileInputStream fis = new FileInputStream(file);
OutputStream fos = response.getOutputStream();
byte[] buffer = new byte[1024*1024*1];
int len = 0;
while((len=fis.read(buffer)) !=-1){
fos.write(buffer, 0, len);
}
fis.close();
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage(),e);
}
}
else{
throw new Exception("文件不存在!![path:"+ file.getAbsolutePath() +"]" );
}
}
}