Newer
Older
huludao / src / main / java / com / newfiber / common / utils / FilesUtils.java
package com.newfiber.common.utils;

import com.newfiber.modules.inspection.entity.FileUploadEntity;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author : huhy on 2018/7/20.
 * @Project_name:pumpingstation
 * @LOCAL:com.xf.station.utils
 * @description:文件的工具类
 */
@Component
public class FilesUtils {

    private final String PATH = System.getProperty("user.dir").concat(File.separator);

    public List<FileUploadEntity> filesUpload(String relationId, MultipartFile[] files) throws IOException {
        List<FileUploadEntity> fileUploadEntities = new ArrayList<>();
        /**上传文件*/
        if (files != null && files.length > 0) {

            for (MultipartFile file : files) {
                List<String> list = this.fileUploadSimple(file, "");
                if (!file.isEmpty()) {

                    String orgFileName = list.get(1);//文件名称
                    String filePath = list.get(2);//文件路径
                    int fileType = Integer.parseInt(list.get(3));//文件类型

                    FileUploadEntity fileUploadEntity = FileUploadEntity.builder()
                            .relationId(relationId)
                            .fileNo(UUID.randomUUID().toString().replace("-", ""))
                            .fileName(orgFileName)
                            .filePath(filePath)
                            .fileType(fileType)
                            .build();
                    fileUploadEntities.add(fileUploadEntity);
                }
            }
        }
        return fileUploadEntities;
    }


    /**
     * @author huhy
     * @ClassName:FilesUtils
     * @date 2018/7/21 11:09
     * @Description: 实现文件上传
     */
    public List<String> fileUploadSimple(MultipartFile file, String path) throws IOException {

        InputStream inputStream = file.getInputStream();
        Integer fileType = FileTypeJudge.isFileType(FileTypeJudge.getType(inputStream));
        if (fileType != 1 && fileType != 2 && fileType != 3 && fileType != 7) {
            throw new IOException("上传文件类型错误");
        }
        if (fileType == 1) path = "picture";
        if (fileType == 2) path = "file";
        if (fileType == 3) path = "video";
        if (fileType == 7) path = "video";

        //获取原始文件名
        String orgName = file.getOriginalFilename();
        //获取文件后缀
        String ext = orgName.substring(orgName.lastIndexOf(".") + 1);
        //文件名MD5加密,获得新文件名
        String newFileName = DigestUtils.md5DigestAsHex((orgName + new Random().nextInt(Integer.MAX_VALUE)).getBytes());
        //拼接文件存储的物理路径
        //String url = projectPath+path+"\\"+DatesUtils.getCurrentDate(true)+"\\"+DatesUtils.getCurrentDate(false)+"\\";
        //存入数据库的路径
        String dbpath = path + File.separator + DateUtils.getCurrentDate(true) + File.separator + DateUtils.getCurrentDate(false) + File.separator + newFileName + "." + ext;
        //物理路径不存在就创建
        mkdirPath(PATH + path);
        File newfile = new File(PATH + dbpath);
        //上传文件
        try {
            file.transferTo(newfile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<String> list = new ArrayList<>();
        list.add(newFileName);
        list.add(orgName);
        list.add(dbpath);
        list.add(fileType + "");
        return list;
    }

    /**
     * @param path    数据库存储的图片路径
     * @param orgName 原始文件名
     *                下载
     */
    public void DownloadFile(String path, String orgName, HttpServletResponse response) throws IOException {
        //设置头为原始文件名
        response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(orgName, "UTF-8"));
        preView(path, response);
    }

    /**
     * 文件预览(浏览器可识别的文件预览,如pdf和图片等。其他文件如word/excel/powerpoint需借助openoffice将其转为pdf再预览)
     *
     * @param path
     * @param response
     * @throws IOException
     */
    public void preView(String path, HttpServletResponse response) throws IOException {
        //获取文件绝对路径
        String filePath = PATH + path;
        InputStream is = new FileInputStream(filePath);
        OutputStream os = response.getOutputStream();
        int len;
        byte[] byt = new byte[1024];
        while (-1 != (len = is.read(byt))) {
            os.write(byt, 0, len);
        }
        os.flush();
        is.close();
        os.close();
    }

    /**
     * @author huhy
     * @ClassName:FilesUtils
     * @date 2018/7/21 10:10 
     * @Description: 获取项目保存文件的路径
     */
    /*public static String projectPath(){
        //截取字符串
        String replceStr = "target/classes/";
        try {
            return URLDecoder.decode(ClassUtils.getDefaultClassLoader().getResource("").getPath().replace(replceStr, ""), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";

    }*/

    /**
     * @author huhy
     * @ClassName:FilesUtils
     * @date 2018/7/21 10:43
     * @Description: 判断文件夹是否存在
     * dirPath:文件夹路径
     */
    public void mkdirPath(String path) {
        //拼接文件存储的物理路径
        String dirPath = path + File.separator + DateUtils.getCurrentDate(true) + File.separator + DateUtils.getCurrentDate(false) + File.separator;
        File dir = new File(dirPath);
        //路径不存在时,创建文件夹
        if (!dir.exists() || !dir.isDirectory()) {
            dir.mkdirs();
        }
    }

    /**
     * 文件删除
     */
    public static void deleat(File file) {
        if (!file.exists()) {
            return;
        }
        //如果是文件,就删除文件
        if (file.isFile()) {
            file.delete();
            return;
        }
        //是文件夹
        if (file.isDirectory()) {
            //循环所有文件夹里面的内容并删除
            File[] files = file.listFiles();
            if (files != null) {
                for (File f : files) {
                    //迭代删除
                    deleat(f);
                }
            }
            //删除自己
            file.delete();
        }
    }

}