1. 文件上传
通用工具类
/**
*
* @param stream 文件输入流
* @param path 保存的文件地址
* @param savefile 文件名
* @throws IOException
*/
public static void SaveFileFromInputStream(InputStream stream, String path, String savefile) throws IOException {
FileOutputStream fs = new FileOutputStream(path + savefile);
byte[] buffer = new byte[1024 * 1024];
int bytesum = 0;
int byteread = 0;
while ((byteread = stream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
fs.flush();
}
fs.close();
stream.close();
}
测试方法
/**
* 上传附件
*/
public Integer uploadFile(MultipartFile file, HttpServletRequest request) {
try {
//获取原始文件名
String fileName = file.getOriginalFilename();
//截取文件后缀
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
//文件名
fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
//保存到服务器的路径
String path = request.getSession().getServletContext().getRealPath("/") + "WEB-INF\\classes\\static\\approval\\";
//文件上传到服务器
UploadImgUtils.SaveFileFromInputStream(file.getInputStream(), path, fileName);
} catch (IOException e) {
log.error(e);
}
}
Controller层
这里测试是上传图片,判断文件是否是图片格式。
//判断图片结尾的正则表达式
public final static String imageFormat = "^.+(.JPEG|.jpeg|.JPG|.jpg|.GIF|.gif|.BMP|.bmp|.PNG|.png)$";
/**
* 上传图片
*/
@PostMapping("/uploadImg")
public Object uploadImg(MultipartFile file, HttpServletRequest req) {
if(file.getOriginalFilename().matches(imageFormat)){
return sysUserService.uploadImg(file, req);
}else {
return Responses.error("只能上传图片文件,请重新选择");
}
}
2.文件下载
通用工具类
/**
*
* @param res
* @param fileName 文件名称
* @param filePath 文件地址
*/
public static void download(HttpServletResponse res, String fileName, String filePath) {
res.setHeader("content-type", "application/octet-stream");
res.setContentType("application/octet-stream");
res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = res.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(new File(filePath
+ fileName)));
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("success");
}
Controller层
@PostMapping("/downloadTemplate")
public Object downloadTemplate(HttpServletResponse res){
try {
//文件名称
String fileName = "importExcelFile.xlsx";
//文件地址
String filePath = "F:\\test";
UploadImgUtils.download(res,fileName,filePath);
} catch (Exception e) {
e.printStackTrace();
}
return Responses.success("");
}
3.文件删除
通用工具类
/**
* 删除文件
* @param filePath 文件完整路径(包括文件名称)
* @return
*/
public static boolean deleteFile(String filePath){
boolean delete_flag = false;
File file = new File(filePath);
if (file.exists() && file.isFile() && file.delete()){
delete_flag = true;
}
else{
delete_flag = false;
}
return delete_flag;
}
Controller层
/**
* 删除
* @param id
* @return
*/
public Object deleteApprovalFile(Integer id) {
if (id != null) {
ApprovalFile approvalFile = approvalFileMapper.selectByPrimaryKey(id);
//approvalFile.getFilePath() 存储文件地址
//approvalFile.getFileName() 存储文件名
//approvalFileMapper.deleteByPrimaryKey(approvalFile.getId()) 删除数据库中数据
if (deleteFile(approvalFile.getFilePath() + approvalFile.getFileName()) && approvalFileMapper.deleteByPrimaryKey(approvalFile.getId()) > 0) {
return Responses.success("删除原文件成功");
}
}
return Responses.error("删除原文件失败");
}
附录
通常项目中获取项目地址的方法
String path = request.getSession().getServletContext().getRealPath("/") + "WEB-INF\\classes\\static\\images\\";
项目中获取服务器ip地址以及端口号、以及项目中的文件展示
主要用于图片的显示
//request.getScheme() 获取 http
//InetAddress.getLocalHost().getHostAddress() 获取ip地址
//request.getServerPort() 获取端口号
//"\\" + "images\\" 获取resources\static\images
String path = request.getScheme() + "://" + InetAddress.getLocalHost().getHostAddress() + ":" + request.getServerPort() + "\\" + "images\\";