文件上传
@RequestMapping(value="/document/addDocument")
public String addDocument(String flag,Document document,HttpSession session) throws Exception, Exception{
if (flag.equals("1")) {
return "document/showAddDocument";
}else {
String path=uploadFile(document, session);
// 上传文件名
String fileName = document.getFile().getOriginalFilename();
// 设置fileName
document.setFileName(fileName);
document.setPath(path+File.separator+ fileName);
// 设置关联的User对象
User user = (User) session.getAttribute(HrmConstants.USER_SESSION);
document.setUser(user);
// 插入数据库
documentService.addDocument(document);
}
return "redirect:/document/selectDocument";
}
uploadFile方法:
public String uploadFile(Document document,HttpSession session) throws Exception, Exception{
// 上传文件路径
String path = session.getServletContext().getRealPath("/upload/"+UUID.randomUUID().toString()+"/");
System.out.println(path);
// 上传文件名
String fileName = document.getFile().getOriginalFilename();
//File.separator:分隔符
File file=new File(path+File.separator+ fileName);
judeDirExists(file);
// 将上传文件保存到一个目标文件当中
document.getFile().transferTo(file);
return path;
}
判断文件夹是否存在,不存在则创建
public static void judeDirExists(File file) {
if (file.exists()) {
if (file.isDirectory()) {
System.out.println("dir exists");
} else {
System.out.println("the same name file exists, can not create dir");
}
} else {
// System.out.println("dir not exists, create it ...");
file.mkdirs();
}
}
文件下载
@RequestMapping(value="/document/downLoad")
public ResponseEntity<byte[]> downLoad(
Integer id,
HttpSession session) throws Exception{
// 根据id查询文档
Document target =documentService.selectById(id);
String fileName = target.getFileName();
// 上传文件路径
String path = target.getPath();
// 获得要下载文件的File对象
File file = new File(path);
// 创建springframework的HttpHeaders对象
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);
// 201 HttpStatus.CREATED
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED);
}
删除文件
@RequestMapping(value="/document/removeDocument")
public String removeDocument(String ids,HttpSession session){
//删除数据库信息
List<Document> documents=documentService.selectDocumentByIds(ids);
documentService.removeDocument(ids);
//删除文件
for (int i = 0; i < documents.size(); i++) {
//文件路径
String path =documents.get(i).getPath();
String name=documents.get(i).getFileName();
//目录路径
String direPath=path.replace(name,"");
direPath=direPath.substring(0,direPath.length()-1);
deleteFile(path, direPath);
}
return "redirect:/document/selectDocument";
}