文件管理大全,springboot操作文件,文件夾的上傳,下載,進度條顯示,新建,刪除,重命名文件

說明

 業務所需,使用web頁面管理服務器上的文件,支持指定目錄,左側顯示目錄樹,右側顯示當前目錄下的所有文件,文件包含文件名,大小,創建時間。 
 開發工具:idea2019 springboot版本:2.0以上 
 前端:vue,ElementUI

頁面展示
在這裏插入圖片描述

1.多文件上傳

Controller層,注意參數,傳遞類型enctype=“multipart/form-data”
/**

  • 上傳多個文件
  • @param request 請求信息
  • @param filePath 上傳文件的路徑
  • @return
    */
    @RequestMapping(value = “/uploadMuilt”, method = RequestMethod.POST)
    public Object uploadMuilt(HttpServletRequest request, String filePath) {
    Map<String, Object> dataMap = new HashMap<>();
    try {
    String str = fileService.uploadMuilt(request, filePath);
    dataMap.put(“data”, str);
    dataMap.put(“code”, 200);
    dataMap.put(“msg”, “多文件上傳成功”);
    } catch (Exception e) {
    e.printStackTrace();
    dataMap.put(“data”, “”);
    dataMap.put(“code”, 500);
    dataMap.put(“msg”, “多文件上傳失敗”);
    }
    return dataMap;
    }

service實現層
/**
 * 多文件上傳
 * @param request
 * @param filePath
 * @return
 */
public String uploadMuilt(HttpServletRequest request,String filePath) {
    List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
    MultipartFile file = null;
    BufferedOutputStream stream = null;
    for (int i = 0; i <files.size() ; i++) {
        file = files.get(i);
        filePath = filePath+"/";
        if(!file.isEmpty()){
            try{
                byte[] bytes = file.getBytes();
                stream = new BufferedOutputStream(new FileOutputStream(
                        new File(filePath+file.getOriginalFilename())
                ));
                stream.write(bytes);
                stream.close();
            }catch(Exception e){
                stream = null;
                e.printStackTrace();
                return "the"+i+"file upload failure";
            }
        }else {
            return "the"+i+"file is empty";
        }
    }
    return "upload multifile success";
}

2. 文件夾上傳

/**
 * 上傳文件夾
 *
 * @param file     待上傳的文件夾
 * @param filePath 要上傳到的目錄路徑
 * @return
 */
@RequestMapping(value = "/uploadFolder", method = RequestMethod.POST)
public Object uploadFolder(MultipartFile[] file, String filePath) {
    Map<String, Object> dataMap = new HashMap<>();
    try {
        FileUtil.saveMultiFile(filePath, file);
        // FileUtil.uploadTest(filePath, file);
        dataMap.put("data", "");
        dataMap.put("code", 200);
        dataMap.put("msg", "文件夾上傳成功");
    } catch (Exception e) {
        dataMap.put("data", "");
        dataMap.put("code", 500);
        dataMap.put("msg", "文件夾上傳失敗");
        e.printStackTrace();
    }

    return dataMap;
}
/**
 * 在basePath下保存上傳的文件夾
 *
 * @param basePath
 * @param files
 */
public static void saveMultiFile(String basePath, MultipartFile[] files) {
    if (files == null || files.length == 0) {
        return;
    }
    if (basePath.endsWith("/")) {
        basePath = basePath.substring(0, basePath.length() - 1);
    }
    for (MultipartFile file : files) {
        String filename = "";
       /* String filename = file.getOriginalFilename();
        String filePath = basePath + "/" + file.getOriginalFilename();*/
        CommonsMultipartFile cf= (CommonsMultipartFile)file;
        FileItem fileItem = cf.getFileItem();
        String fileStr = fileItem.toString();
        String[] split = fileStr.split(",");
        for (int i = 0; i <split.length ; i++) {
            if(split[i].contains("name=")){
                 filename = split[i].substring(5,split[i].length());
            }
        }
        String filePath = basePath + "/" + filename;
        makeDir(filePath);
        File dest = new File(filePath);
        try {
            file.transferTo(dest);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
    }
}

3.文件上傳的進度條實現

在啓動類上加上註解,使用自定義的文件上傳解析

package com.filemanager.fm;

import com.filemanager.fm.config.CustomMultipartResolver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.web.multipart.MultipartResolver;

import java.io.IOException;

//注意取消自動Multipart配置,否則可能在上傳接口中拿不到file的值
@SpringBootApplication
@EnableAutoConfiguration(exclude = { MultipartAutoConfiguration.class })
public class FmApplication extends SpringBootServletInitializer{

    //注入自定義的文件上傳處理類
    @Bean(name = "multipartResolver")
    public MultipartResolver multipartResolver() {
        CustomMultipartResolver customMultipartResolver = new CustomMultipartResolver();
        return customMultipartResolver;
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(FmApplication.class);
    }

    public static void main(String[] args) throws IOException {
        SpringApplication.run(FmApplication.class, args);
        
    }

}

編寫自定義文件渲染的配置

package com.filemanager.fm.config;

import com.filemanager.fm.listener.UploadProgressListener;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
public
class CustomMultipartResolver extends CommonsMultipartResolver {

    @Autowired
    private UploadProgressListener progressListener;

    @Override
    protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
        String encoding = super.determineEncoding(request);
        progressListener.setSession(request.getSession());
        FileUpload fileUpload = prepareFileUpload(encoding);
        fileUpload.setProgressListener(progressListener);
        try {
            List<FileItem> fileItemList =  ((ServletFileUpload)fileUpload).parseRequest(request);
            return super.parseFileItems(fileItemList, encoding);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        return null;
    }
}

編寫監聽器,需實現ProgressListener 接口

package com.filemanager.fm.listener;


import com.filemanager.fm.model.Progress;
import org.apache.commons.fileupload.ProgressListener;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;

@Component
public class UploadProgressListener implements ProgressListener {

    private HttpSession session;

    public void setSession(HttpSession session){
        this.session = session;
        Progress pe = new Progress();
        session.setAttribute("uploadStatus", pe);
    }


    /**
     *  設置當前已讀取文件的進度
     * @param readBytes 已讀的文件大小(單位byte)
     * @param allBytes 文件總大小(單位byte)
     * @param index 正在讀取的文件序列
     */
    @Override
    public void update(long readBytes, long allBytes, int index) {
        Progress pe = (Progress) session.getAttribute("uploadStatus");
        pe.setReadBytes(readBytes);
        pe.setAllBytes(allBytes);
        pe.setCurrentIndex(index);
    }
}

編寫進度條實體類

package com.filemanager.fm.model;

public class Progress {
    private long ReadBytes; //已讀取文件的比特數
    private long contentLength;//文件總比特數
    private long items; //正讀的第幾個文件

    public long getReadBytes() {
        return ReadBytes;
    }

    public void setReadBytes(long readBytes) {
        ReadBytes = readBytes;
    }

    public long getContentLength() {
        return contentLength;
    }

    public void setContentLength(long contentLength) {
        this.contentLength = contentLength;
    }

    public long getItems() {
        return items;
    }

    public void setItems(long items) {
        this.items = items;
    }

    public void setAllBytes(long allBytes) {
    }

    public void setCurrentIndex(int index) {
    }
}

4.根據根目錄的路徑,遞歸獲取改目錄下的所有目錄

/**
 * 獲取路徑下的所有文件/文件夾
 *
 * @return
 */
public  List<String> getAllDirection(String filePath) {
    if(filePath == null || "".equals(filePath)){
        filePath = dirPath;
    }
    List<String> dirList = getAllDirs(filePath, true);
    return dirList;
}

5.根據目錄的路徑,獲取改目錄下的所有文件信息詳情

/**
 * 獲取路徑下的所有文件
 *
 * @param directoryPath 需要遍歷的文件夾路徑
 * @return
 */
public  List<Object> getAllFiles(String directoryPath) {
    List<Object> list = new ArrayList<Object>();
    File baseFile = new File(directoryPath);
    if (baseFile.isFile() || !baseFile.exists()) {
        return list;
    }
    File[] files = baseFile.listFiles();
    for (File file : files) {
        Map<String, String> map = new HashMap<>();
        if (file.isFile()) {
            map.put("fileName", file.getName());
            map.put("filePath", file.getAbsolutePath());
            map.put("time", getFileTime(file.getAbsolutePath()));
            map.put("size", getFileSize(file.getAbsolutePath()));
            list.add(map);
        }
    }
    return list;
}

根據文件路徑獲取該文件的創建時間,即是文件的最後一次修改時間

/**
 * 獲取文件最後修改時間
 */
public  String getFileTime(String filePath) {
    File file = new File(filePath);
    long time = file.lastModified();//返回文件最後修改時間,是以個long型毫秒數
    String ctime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date(time));
    return ctime;
}

把文件的大小轉成KB,MB,GB等字符串

/**
 * 獲取文件大小,整數
 */
public  String getFileSize(String path) {
    File file = new File(path);
    long length = file.length();
    return FormetFileSize(length);
}

/**
 * 轉換文件大小,帶單位的字符串
 *
 * @param fileLength 文件大小值
 * @return String 文件大小
 * @Title: FormetFileSize
 * @author projectNo
 */
public  String FormetFileSize(long fileLength) {
    DecimalFormat df = new DecimalFormat("#.00");
    DecimalFormat d = new DecimalFormat("#");
    String fileSizeString = "";
    if (fileLength < 1024) {
        fileSizeString = d.format((double) fileLength) + "B";
    } else if (fileLength < 1048576) {
        fileSizeString = df.format((double) fileLength / 1024) + "KB";
    } else if (fileLength < 1073741824) {
        fileSizeString = df.format((double) fileLength / 1048576) + "MB";
    } else {
        fileSizeString = df.format((double) fileLength / 1073741824) + "GB";
    }
    return fileSizeString;
}

6.創建文件夾,名字重複就在後面加name(1),name(2)採用windows文件重命名方法

/**
 * 創建多級目錄
 *
 * @param path
 */
public static boolean makeDirs(String path) {
    File file = new File(path);
    boolean flag = false;
    try {
        // 如果文件夾不存在則創建
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
            flag = true;
        }else{
            int i = 1;
            String name = path.substring(path.lastIndexOf("/")+1,path.length());
            while(file.exists()) {
                String newFilename = name+"("+i+")";
                String parentPath = file.getParent();
                file = new File(parentPath+ File.separator+newFilename);
                i++;

            }
            file.mkdirs();
            flag = true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return flag;
}

7.修改文件夾名稱,也支持修改文件名

/**
 * 通過文件路徑直接修改文件名,支持文件,目錄
 *
 * @param filePath    需要修改的文件的完整路徑
 * @param newFileName 需要修改的文件的名稱
 * @return
 */
public String FixFileName(String filePath, String newFileName) {
    File f = new File(filePath);
    if (!f.exists()) { // 判斷原文件是否存在(防止文件名衝突)
        return null;
    }
    newFileName = newFileName.trim();
    if ("".equals(newFileName) || newFileName == null) // 文件名不能爲空
        return null;
    String newFilePath = null;
    if (f.isDirectory()) { // 判斷是否爲文件夾
        int i = filePath.lastIndexOf("\\");
        //windows系統使用\\分割,linux使用/分割
        newFilePath = filePath.substring(0, filePath.lastIndexOf("/")) + "/" + newFileName;
    } else {
        newFilePath = filePath.substring(0, filePath.lastIndexOf("/")) + "/" + newFileName
                + filePath.substring(filePath.lastIndexOf("."));
    }
    File nf = new File(newFilePath);
    try {
        f.renameTo(nf); // 修改文件名
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return newFilePath;
}

8.遞歸刪除文件夾及其子文件

/**
 * 刪除目錄及其子文件夾
 *
 * @param rootFilePath 根目錄
 * @return boolean
 */
public boolean deleteFile(File rootFilePath) {
    if (rootFilePath.isDirectory()) {
        for (File file : rootFilePath.listFiles()) {
            deleteFile(file);
        }
    }
    return rootFilePath.delete();
}

9.文件下載

/**
 * 文件下載
 *
 * @param response
 * @param filePath 被下載的文件在服務器中的路徑
 * @return
 * @throws UnsupportedEncodingException
 */
@RequestMapping(value = "/download", method = RequestMethod.POST)
private String download(HttpServletResponse response, String filePath) throws UnsupportedEncodingException {
    File file = new File(filePath);
    String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);//被下載文件的名稱
    if (file.exists()) {
        response.setContentType("application/force-download");// 設置強制下載不打開
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ";filename*=utf-8''"
                + URLEncoder.encode(fileName, "UTF-8"));

        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream outputStream = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                outputStream.write(buffer, 0, i);
                i = bis.read(buffer);
            }

            return "下載成功";
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return "下載失敗";
}

10.githup完整代碼下載

11.結束語

支持開源,少搬磚頭

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章