package com.rbpm.service.Impl;
import ch.qos.logback.core.spi.ScanException;
import com.rbpm.service.FileService;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
@Service
public class FileServiceImpl implements FileService {
// 文件上傳根目錄
@Value("${UPLOAD_URL}")
private String UPLOAD_URL;
// 下載的文件的根路徑
@Value("${download_URL}")
private String download_URL;
private Logger m_Logger = LoggerFactory.getLogger("FileServiceImpl");
private Integer m_Index = 0;
/**
* @Description: 單文件上傳
* @Author:
* @Date: 2018/4/9 17:15
*/
public String upload(MultipartFile file) {
try {
if (file.isEmpty()) {
return "文件爲空";
}
// 獲取文件名
String fileName = file.getOriginalFilename();
m_Logger.info("上傳的文件名爲:" + fileName);
// 獲取文件的後綴名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
m_Logger.info("文件的後綴名爲:" + suffixName);
// 設置文件存儲路徑
String filePath = UPLOAD_URL;
String path = filePath + fileName + suffixName;
File dest = new File(path);
// 檢測是否存在目錄
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();// 新建文件夾
}
file.transferTo(dest);// 文件寫入
return "上傳成功";
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "上傳失敗";
}
/**
* @Description: 創建文件夾
* @Author:
* @Date: 2018/4/9 17:15
*/
public Map addFileFolder(HttpServletRequest request, String Path) {
Map tResultMap = new HashMap();
String mkDirectoryPath = Path; // 路徑格式:"d:\\aim\\y"
File file = null;
int j = 1;
try {
file = new File(Path);
if (!file.exists()) {
file.mkdirs();
} else {
while (file.exists()) {
mkDirectoryPath = Path + "-副本(" + getNum(j, Path) + ")";
file = new File(mkDirectoryPath);
file.mkdirs();
break;
}
}
tResultMap.put("msg", "建立成功");
System.out.println(mkDirectoryPath + "建立完畢");
} catch (Exception e) {
tResultMap.put("msg", "建立失敗");
System.out.println(mkDirectoryPath + "建立失敗");
} finally {
file = null;
}
return tResultMap;
}
public int getNum(int i, String Path) {
String path = Path + "-副本(" + i + ")";
File file = new File(path);
if (file.exists()) {
i++;
return getNum(i, Path);
} else {
return i;
}
}
/**
* @Description: 上傳多個文件
* @Author: Mr.Zhong
* @Date: 2018/4/9 17:26
*/
public String uploads(HttpServletRequest request, MultipartFile[] file) {
try {
//上傳目錄地址
String uploadDir = request.getSession().getServletContext().getRealPath("/") + "upload/";
//如果目錄不存在,自動創建文件夾
File dir = new File(uploadDir);
if (!dir.exists()) {
dir.mkdir();
}
//遍歷文件數組執行上傳
for (int i = 0; i < file.length; i++) {
if (file[i] != null) {
//調用上傳方法
executeUpload(uploadDir, file[i]);
}
}
} catch (Exception e) {
//打印錯誤堆棧信息
e.printStackTrace();
return "上傳失敗";
}
return "上傳成功";
}
/**
* 上傳方法爲公共方法
*/
private void executeUpload(String uploadDir, MultipartFile file) throws Exception {
//文件後綴名
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//上傳文件名
String filename = UUID.randomUUID() + suffix;
//服務器端保存的文件對象
File serverFile = new File(uploadDir + filename);
//將上傳的文件寫入到服務器端文件內
file.transferTo(serverFile);
}
/**
* @Description: 掃描文件(根據父級目錄查當前目錄下的文件和文件夾)
* @Author:
* @Date: 2018/4/9 17:39
*/
private static ArrayList<Object> scanFiles = new ArrayList<Object>();
public Map scanFilesWithRecursion(String folderPath) throws ScanException {
folderPath = UPLOAD_URL;
folderPath.length();
HashMap tResultMap = new HashMap();
tResultMap.put("status", "failed");
ArrayList<String> dirctorys = new ArrayList<String>();
File directory = new File(folderPath);
if (!directory.isDirectory()) {
throw new ScanException('"' + folderPath + '"' + " input path is not a Directory , please input the right path of the Directory. ^_^...^_^");
}
File[] filelist = directory.listFiles();
List tFolderList = new ArrayList();
List tFilesList = new ArrayList();
for (File tFile : filelist) {
/**如果當前是文件夾,進入遞歸掃描文件夾**/
if (tFile.isDirectory())
tFolderList.add(tFile.getName());
else {
tFilesList.add(tFile.getName());
}
}
tResultMap.put("folder", tFolderList);
tResultMap.put("files", tFilesList);
tResultMap.put("status", "success");
return tResultMap;
}
/**
* @Description: 獲取目錄樹
* @Author:
* @Date: 2018/4/9 17:39
*/
public Map scanFilesWithNoRecursion(String folderPath) {
Map tResultMap = new HashMap();
m_Index = 0;
tResultMap.put("data", recursion(folderPath));
return tResultMap;
}
/**
* @Description: 獲取目錄樹的處理方法
* @Author:
* @Date: 2018/4/9 17:39
*/
public List recursion(String vFolderPath) {
List tResultList = new ArrayList();
File directory = new File(vFolderPath);
File[] tfiles = directory.listFiles();
for (File tFile : tfiles) {
Map tMap = new HashMap();
if (tFile.isDirectory()) {
tMap.put("children", recursion(vFolderPath + "/" + tFile.getName()));
tMap.put("label",tFile.getName());
tMap.put("id", ++m_Index);
tResultList.add(tMap);
}
}
return tResultList;
}
/**
* @Description: 下載
* @Author:
* @Date: 2018/4/9 17:39
*/
public Map download(HttpServletResponse res) {
Map tResultMap = new HashMap();
String fileName = download_URL;
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(UPLOAD_URL
+ 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");
return tResultMap;
}
/**
* @Description: 文件或文件夾重命名
* @Author:
* @Date: 2018/4/9 17:39
*/
public Map updateFileName(String Path , String newPath) {
Map tResultMap = new HashMap();
//想命名的原文件的路徑
File file = new File(Path);
if(file.exists()) {
file.renameTo(new File(newPath));
tResultMap.put("msg","修改文件名成功");
}
return tResultMap;
}
public Map deleteDirectory(List<String> pathList) {
Map tResultMap = new HashMap();
tResultMap.put("status","failed");
for (int i=0;i<pathList.size();i++){
deleteDirectoryDetail(UPLOAD_URL+pathList.get(i));
}
tResultMap.put("status","success");
return tResultMap;
}
/**
* 刪除文件和文件夾
* @param path
* @return
*/
public Map deleteDirectoryDetail(String path){
Map tResultMap = new HashMap();
//tResultMap.put("status","failed");
// 如果dir不以文件分隔符結尾,自動添加文件分隔符
if (!path.endsWith(File.separator))
path = path + File.separator;
File dir = new File(path);
try {
if(dir.exists()){
File[] tmp=dir.listFiles();
for(int i=0;i<tmp.length;i++){
if(tmp[i].isDirectory()){
deleteDirectoryDetail(path+"/"+tmp[i].getName());
}
else{
tmp[i].delete();
System.out.println(tmp[i]+"刪除成功");
}
}
dir.delete();
System.out.println(dir+"刪除成功");
}
//tResultMap.put("status","success");
}catch (Exception e){
e.printStackTrace();
tResultMap.put("msg",e.getMessage());
}finally {
return tResultMap;
}
}
}