一、上传文件至tomcat服务器
步骤
- 编写工具类
- 后台接口获取前端上传的文件
- 调用工具类的方法
编写工具类UploadUtil.java
/**
* 以流的方式上传文件
* @param path
* @param multipartFile
* @param packageName
* @return
*/
public String upload(String path,MultipartFile multipartFile,String packageName){
//获取文件名,如a.jpg
String originalFilename = multipartFile.getOriginalFilename();
//判断是否为空
if (originalFilename==null){
return null;
}
//拼接文件目录
String dir2 = packageName;
String dir = path + File.separator+dir2;
//把路径丢到File文件中
File file = new File(dir);
//若文件夹不存在,则创建该文件夹
if (!file.exists()){
file.mkdirs();
}
//生成新的UUID.randomUUID().toString():为了防止文件名重复
String newFileName = UUID.randomUUID().toString().replace("-","")+"."+originalFilename.substring(originalFilename.lastIndexOf(".")+1);
InputStream is = null;
OutputStream os = null;
try {
is = multipartFile.getInputStream();
os = new FileOutputStream(dir+File.separator+newFileName);
//对文件进行复制
FileCopyUtils.copy(is,os);
} catch (IOException e) {
e.printStackTrace();
}finally {
if (is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//返回文件的路径,以便保存到数据库中
return dir2+File.separator+newFileName;
}
controller接口
@RequestMapping("geUploadStationFile")
@ResponseBody
JSONObject addFile(HttpServletRequest request,
@RequestParam("multipartFile")MultipartFile multipartFile,
String packageName)
{
JSONObject job = new JSONObject();
try {
if (multipartFile.isEmpty()){
throw new Exception("文件异常");
}
//对返回的结果进行处理
String res=stationFileService.insertStationFile(multipartFile,packageName,version);
job.element("message", res);
} catch (Exception e) {
//捕获异常,进行处理
job.element("message", e.getMessage());
}
return job;
}
调用工具类
//定义tomcat文件上传路径
private static final String UPLOAD_DIR= System.getProperty("catalina.home")+"\\webapps\\upload";
public boolean insertStationFile(MultipartFile multipartFile,String packageName)throws Exception {
//文件保存路径
String filePath = uploadUtils.upload(UPLOAD_DIR, multipartFile,packageName);
//返回的路径可存入数据库
return filePath;
}
二、从tomcat服务器删除文件
编写工具类中的删除方法
/**
* 从tomcat服务器删除文件
* @param pathArr
* @param dir
* @return
*/
public boolean delete(String[] pathArr,String dir) {
int len = pathArr.length;
int count = 0;
for (String path : pathArr) {
//拼接文件完整路径
String abpath = dir+ File.separator + path;
//获取需要删除的文件
File deleteFile = new File(abpath);
if (deleteFile.exists() && deleteFile.isFile() && deleteFile.delete() == true) {
count++;
}
}
return count==len ? true:false;
}
调用方法与同上传到服务器