VUE+elementui照片上传和zip压缩包上传后端目录解压

 

1.Vue代码

<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="85px">
      <el-form-item label="工号" prop="userCode">
        <el-input v-model="queryParams.userCode" placeholder="请输入工号" clearable size="small"
          @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="姓名" prop="nickName">
        <el-input v-model="queryParams.nickName" placeholder="请输入姓名" clearable
          size="small" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="部门" prop="deptName">
        <el-input v-model="queryParams.deptName" placeholder="请输入部门" clearable
          size="small" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="info" icon="el-icon-upload" size="mini" @click="handleImport" v-hasPermi="['riskPredictionData:roster:batchUploadPhoto']">批量上传</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="false">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['riskPredictionData:roster:uploadPhoto']"
        >上传照片</el-button>
      </el-col>
    </el-row>

    <el-table ref="reportSupplier" :key="tamptime" :max-height="tableHeight" v-loading="loading" :data="rosterList" >
      <el-table-column type="index" width="55" label="序号" align="center" />
      <el-table-column label="工号" align="center" prop="userCode" />
      <el-table-column label="姓名" align="center" prop="nickName" />
      <el-table-column label="部门" align="center" prop="deptName" show-overflow-tooltip />
      <el-table-column label="职位" align="center" prop="position" show-overflow-tooltip v-if="false"/>
      <el-table-column label="职务" align="center" prop="post"  show-overflow-tooltip/>
      <el-table-column label="头像" align="center" prop="photo" >
        <template slot-scope="scope">
          <el-image :src="baseUrl + '/profile/upload/cadrePhoto/' + scope.row.userCode +'.jpg/'" style="height:50px;width:50px" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['riskPredictionData:roster:uploadPhoto']"
          >上传照片</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

     <!-- 花名册入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open"  width="400px">
      <el-upload ref="upload" :limit="1"  accept=".zip" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess" :auto-upload="false" drag >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处,或
          <em>点击上传</em>
        </div>
        <div
          class="el-upload__tip"
          slot="tip"
        >
          <!-- <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据 -->
<!--          <el-link
            type="info"
            style="font-size:12px"
            @click="importTemplate"
          >下载模板</el-link>-->
        </div>
        <div
          class="el-upload__tip"
          style="color:red"
          slot="tip"
        >提示:仅允许导入“zip”格式文件!</div>
      </el-upload>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="submitFileForm"
        >确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改成员照对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" v-dialog-drag :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="95px">
        <el-form-item label="工号" prop="userCode">
          {{form.userCode}}
        </el-form-item>
<!--        <el-form-item label="上传证件照" prop="photo">
          <el-upload class="upload-demo"
                     ref="upload"
                     accept=".jpg"
                     :action="uploadPhoto.url+form.userCode"
                     :headers="uploadPhoto.headers"
                     :before-upload="handleBefore"
                     :on-remove="handleRemove"
                     :on-success="(res, file)=>{handleSuccess( res, file)}"
                     :show-file-list="false"
          >
            <el-button slot="trigger" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">上传文件不能超过10M</div>
          </el-upload>
          <el-image style="width: 100px; height: 100px" :src="uploadPhoto.imgUrl" fit="fill"></el-image>
        </el-form-item>-->
        <el-form-item label="上传照片" prop="photo">
          <el-upload
            ref="uploadPhoto"
            class="avatar-uploader"
            :key="tamptimeUploadPhoto"
            :action="uploadPhoto.url+form.userCode"
            :headers="uploadPhoto.headers"
            :show-file-list="false"
            :on-success="(res, file)=>{handleSuccess( res, file)}"
            :before-upload="handleBefore"
            :auto-upload="true">
            <img v-if="uploadPhoto.isShowPhoto" :src="uploadPhoto.imgUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {listRoster, getRoster, exportRoster, importTemplate}
  from "@/api/hr/riskPrediction/data/roster";
import { getToken } from "@/utils/auth";
import store from "@/store";
import axios from "axios";
export default {
  name: "CadrePhoto",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      tableHeight:0,
      // 员工风险预判-花名册导入
      rosterList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userCode: undefined,
        nickName: undefined,
        deptName: undefined,
        post: '部门负责人',
      },
      // 表单参数
      form: {
        userCode: undefined,
        photo: undefined,
      },
      // 表单校验
      rules: {
        userCode: [
          { required: true, message: "工号不能为空", trigger: "blur" }
        ],
        nickName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
      },
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "批量上传",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/riskPrediction/data/roster/batchUpload"
      },
      options: {
        img: store.getters.avatar, //裁剪图片的地址
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 200, // 默认生成截图框宽度
        autoCropHeight: 200, // 默认生成截图框高度
        fixedBox: true // 固定截图框大小 不允许改变
      },
      uploadPhoto: {
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/riskPrediction/data/roster/upload/",
        imgUrl: '',
        isShowPhoto: false,
      },
      baseUrl: process.env.VUE_APP_BASE_API,
      tamptime:new Date().valueOf(),
      tamptimeUploadPhoto:new Date().valueOf(),
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    // 设置表格最大高度
    this.$nextTick(() => {
      //屏幕可视化高度-表格上方高度-需求空出高度
      this.tableHeight = window.innerHeight - this.$refs.reportSupplier.$el.offsetTop - 140;
    });
  },
  methods: {
    /** 导入按钮操作 */
    handleImport () {
      this.upload.title = "批量导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress (event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess (response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      if(this.strIsEmpty(response.msg)){
        this.$message({
          message: '请使用模板导入',
          type: 'warning'
        });
        return
      }
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    /** 下载模板操作 */
    importTemplate () {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 提交上传文件
    submitFileForm () {
      this.$refs.upload.submit();
    },
    /** 查询员工风险预判-花名册导入 */
    getList() {
      this.loading = true;
      this.tamptime = new Date().valueOf()
      listRoster(this.queryParams).then(response => {
        this.rosterList = response.rows;
        this.total = response.total;
        this.loading = false;
        // 数据并不会更新, 随便调用一下页面事件,什么事件都可以,聚焦等都可以,这里使用 element 表格自带的高亮行事件
        this.$refs.reportSupplier.setCurrentRow(this.rosterList[0])
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userCode = row.userCode
      const _that = this
      getRoster(userCode).then(response => {
        this.form = response.data;
        if(this.form.userCode){
          this.uploadPhoto.imgUrl = process.env.VUE_APP_BASE_API + "/profile/upload/cadrePhoto/" + this.form.userCode +'.jpg'
          axios.get(_that.uploadPhoto.imgUrl)
          .then(function (response) {
            if(response.status == 200){
              _that.uploadPhoto.isShowPhoto = true;
            }
          })
          .catch(function (error) {
            // 处理请求失败的结果
          });
          /*getImgUrl(this.uploadPhoto.imgUrl).then(response=>{
            if(response.status == 200){
              uploadPhoto.isShowPhoto = true;
            }
          }).catch(error => {
          })*/
        }
        this.open = true;
        this.title = "修改照片";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.getList()
    },
    /** 提交按钮 */
    submitForm: function() {
      this.open = false;
      this.getList()
      //this.$refs.uploadPhoto.submit();
    },
    reset(){
      this.form = {
       userCode : undefined,
       photo: undefined,
      },
      this.uploadPhoto = {
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/riskPrediction/data/roster/upload/",
        imgUrl: '',
        isShowPhoto: false,
      }
    },
    handleBefore (file) {
      var fileExtension = file.name.substring(file.name.lastIndexOf('.') + 1);
      if (["jpg"].indexOf(fileExtension) == -1) {
        //文件类型
        this.$message({
          message: "不支持上传." + fileExtension+ "类型的附件",
          type: 'warning'
        })
        return false;
      }
      if ( file.size > 10485760) {
        //文件不能大于10M
        this.$message({
          message: "上传附件不能大于10M",
          type: 'warning'
        })
        return false;
      }
    },
    handleRemove(file, fileList) {
    },
    handleSuccess(res, file){
      if (res.code === 200) {
        this.uploadPhoto.imgUrl = res.url
        this.form.photo =file.fileName
        this.uploadPhoto.isShowPhoto = true;
        this.tamptimeUploadPhoto = new Date().valueOf()
      }else{
        this.uploadPhoto.imgUrl = null
        this.form.photo = null
      }
    },
    getImgUrl(){
      return this.uploadPhoto.imgUrl
    }

  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

2.roster.js代码

import request from '@/utils/request'

// 查询员工风险预判-花名册导入+员工基础信息列表
export function listRoster(query) {
  return request({
    url: '/riskPrediction/data/roster/list',
    method: 'get',
    params: query
  })
}

// 查询员工风险预判-花名册导入+员工基础信息详细
export function getRoster(userCode) {
  return request({
    url: '/riskPrediction/data/roster/' + userCode,
    method: 'get'
  })
}


// 导出员工风险预判-花名册导入+员工基础信息
export function exportRoster(query) {
  return request({
    url: '/riskPrediction/data/roster/export',
    method: 'get',
    params: query
  })
}

// 下载模板
export function importTemplate() {
  return request({
    url: '/riskPrediction/data/roster/importTemplate',
    method: 'get'
  })
}

3.auth.js代码

import Cookies from 'js-cookie'
import router from './../router'
import store from '@/store'

const TokenKey = 'Admin-Token'


const ssoToken = 'sso_session';



export function getAuthHeader() {
  let header = {};
  if (getToken()) {
    header['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  let route = router.currentRoute;
  if (route && route.meta && route.meta.roleIds) {
    header['routerRoleIds'] = route.meta.roleIds // 让每个请求携带权限表示
  } 
  return header;
}


export function getRedirectRoutePath(toRoute) {
  if(!toRoute) {
    return  {path:"/"};
  }
  let toPath = toRoute.path;
  const permissionRoutes = store.getters && store.getters.permission_routes
  if (!permissionRoutes || permissionRoutes.length < 1) {
    return {path:"/"};
  }
  if (toPath == "/") {
    let permissionRootPaths = permissionRoutes.filter(route=>{
      if (route.path  == ""  && route.children 
      && route.children.length > 0 ) {
        let t = route.children[0];
        return t.path == "/bgBoard"
      }
      return false;
    })
    if (permissionRootPaths.length > 0) {
      let t = permissionRootPaths[0].children[0];
      return {path:t.path};
    }
    return {path:"/index"};
  }
  return toRoute;
}

export function getToken() {
  return Cookies.get(TokenKey)
}

export function setToken(token) {
  return Cookies.set(TokenKey, token)
}

export function removeToken() {
  return Cookies.remove(TokenKey)
}

export function getSSOToken() {
  return Cookies.get(ssoToken)
}

export function setSSOToken(token) {
  return Cookies.set(ssoToken, token)
}

export function removeSSOToken() {
  return Cookies.remove(ssoToken)
}

4.后端代码

package com.goertek.riskPrediction.data.controller;

import com.goertek.framework.aspectj.lang.enums.BusinessType;
import com.goertek.framework.config.GoerTekConfig;
import com.goertek.framework.config.ServerConfig;
import com.goertek.framework.utils.poi.ExcelUtil;
import com.goertek.framework.web.controller.BaseController;
import com.goertek.framework.web.domain.AjaxResult;
import com.goertek.framework.web.page.TableDataInfo;
import com.goertek.hrLog.HrLog;
import com.goertek.hrUtils.CadreFileUploadUtils;
import com.goertek.riskPrediction.data.domain.HrRiskPredictionImportRoster;
import com.goertek.riskPrediction.data.service.IHrRiskPredictionImportRosterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

/**
 * 员工风险预判-花名册导入Controller
 * 
 * @author xx
 * @date 2021-08-30
 */
@RestController
@RequestMapping("/riskPrediction/data/roster")
public class HrRiskPredictionImportRosterControllerTest extends BaseController
{
    @Autowired
    private ServerConfig serverConfig;

    /**
     * 照片上传请求
     */
    @HrLog(title = "照片上传", businessType = BusinessType.IMPORT)
    @PostMapping("/upload/{userCode}")
    public AjaxResult uploadFile(MultipartFile file,@PathVariable("userCode") String userCode) throws Exception
    {
        try
        {
            String originalFilename = userCode + ".jpg";
            // 上传文件路径
            String filePath = GoerTekConfig.getUploadPath()+ "/cadrePhoto";;
            // 上传并返回新文件名称
            String fileName = CadreFileUploadUtils.upload(filePath, file, originalFilename);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            ajax.put("realName", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    @HrLog(title = "批量导入", businessType = BusinessType.IMPORT)
    @PostMapping("/batchUpload")
    public AjaxResult batchUpload(MultipartFile file, boolean updateSupport) throws Exception
    {
        try
        {
            String originalFilename = file.getOriginalFilename();
            // 上传文件路径
            String filePath = GoerTekConfig.getUploadPath()+ "/cadrePhoto";;
            // 上传并返回新文件名称
            String fileName = CadreFileUploadUtils.upload(filePath, file, originalFilename);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            ajax.put("realName", file.getOriginalFilename());
            //解压
            File zipFile = new File(filePath+"/"+originalFilename);
            File destDir = new File(filePath);
            CadreFileUploadUtils.zipDecompress(zipFile,destDir);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }




}
5.CadreFileUploadUtils.java
package com.goertek.hrUtils;

import com.goertek.framework.config.GoerTekConfig;
import com.goertek.framework.constant.Constants;
import com.goertek.framework.exception.file.FileNameLengthLimitExceededException;
import com.goertek.framework.exception.file.FileSizeLimitExceededException;
import com.goertek.framework.exception.file.InvalidExtensionException;
import com.goertek.framework.utils.DateUtils;
import com.goertek.framework.utils.StringUtils;
import com.goertek.framework.utils.file.MimeTypeUtils;
import com.goertek.framework.utils.security.Md5Utils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * 文件上传工具类
 *
 * @author admin
 */
public class CadreFileUploadUtils {

    /**
     * 默认的文件名最大长度 100
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;

    /**
     * 默认上传的地址
     */
    private static String defaultBaseDir = GoerTekConfig.getProfile();

    private static int counter = 0;

    public static void setDefaultBaseDir(String defaultBaseDir) {
        CadreFileUploadUtils.defaultBaseDir = defaultBaseDir;
    }

    public static String getDefaultBaseDir() {
        return defaultBaseDir;
    }

    /**
     * 以默认配置进行文件上传
     *
     * @param file 上传的文件
     * @return 文件名称
     * @throws Exception
     */
    public static final String upload(MultipartFile file, String fileName) throws IOException {
        try {
            return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, fileName);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file    上传的文件
     * @return 文件名称
     * @throws IOException
     */
    public static final String upload(String baseDir, MultipartFile file, String fileName) throws IOException {
        try {
            return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, fileName);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }



    /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file    上传的文件
     * @return 文件名称
     * @throws IOException
     */
    public static final String uploadWithoutDate(String baseDir, MultipartFile file) throws IOException {
        try {
            int fileNamelength = file.getOriginalFilename().length();
            if (fileNamelength > com.goertek.framework.utils.file.FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
                throw new FileNameLengthLimitExceededException(com.goertek.framework.utils.file.FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
            }

            // assertAllowed(file, allowedExtension);

            String fileName =  file.getOriginalFilename();
            File desc = getAbsoluteFile(baseDir, fileName);
            file.transferTo(desc);
            String pathFileName = getPathFileName(baseDir, fileName);
            return pathFileName;
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }


    /**
     * 文件上传
     *
     * @param baseDir 相对应用的基目录
     * @param file    上传的文件
     * @return 返回上传成功的文件名
     * @throws FileSizeLimitExceededException       如果超出最大大小
     * @throws FileNameLengthLimitExceededException 文件名太长
     * @throws IOException                          比如读写文件出错时
     * @throws InvalidExtensionException            文件校验异常
     */
    public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension, String fileName)
            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
            InvalidExtensionException {
        int fileNamelength = file.getOriginalFilename().length();
        if (fileNamelength > CadreFileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
            throw new FileNameLengthLimitExceededException(CadreFileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }


        //String fileName = extractFilename(file);
        //String fileName = file.getOriginalFilename();

        File desc = getAbsoluteFile(baseDir, fileName);
        file.transferTo(desc);
        String pathFileName = getPathFileName(baseDir, fileName);
        return pathFileName;
    }

    /**
     * 编码文件名
     */
    public static final String extractFilename(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        fileName = DateUtils.datePath() + "/" + encodingFilename(fileName) + "." + extension;
        return fileName;
    }



    private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        if (!desc.exists()) {
            desc.createNewFile();
        }else{
            desc.createNewFile();
        }
        return desc;
    }

    private static final String getPathFileName(String uploadDir, String fileName) throws IOException {
        int dirLastIndex = GoerTekConfig.getProfile().length() + 1;
        String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
        String pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
        return pathFileName;
    }

    /**
     * 编码文件名
     */
    private static final String encodingFilename(String fileName) {
        fileName = fileName.replace("_", " ");
        fileName = Md5Utils.hash(fileName + System.nanoTime() + counter++);
        return fileName;
    }

    /**
     * 文件大小校验
     *
     * @param file 上传的文件
     * @return
     * @throws FileSizeLimitExceededException 如果超出最大大小
     * @throws InvalidExtensionException
     */
    public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
            throws FileSizeLimitExceededException, InvalidExtensionException {
        long size = file.getSize();

        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
            if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) {
                throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
                        fileName);
            } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) {
                throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
                        fileName);
            } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) {
                throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
                        fileName);
            } else {
                throw new InvalidExtensionException(allowedExtension, extension, fileName);
            }
        }

    }

    /**
     * 判断MIME类型是否是允许的MIME类型
     *
     * @param extension
     * @param allowedExtension
     * @return
     */
    public static final boolean isAllowedExtension(String extension, String[] allowedExtension) {
        for (String str : allowedExtension) {
            if (str.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static final String getExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension)) {
            extension = MimeTypeUtils.getExtension(file.getContentType());
        }
        return extension;
    }


    public static String getUploadFile(String url) {
        if (!url.startsWith("/")) {
            url = "/" + url;
        }
        if (url.startsWith(Constants.RESOURCE_PREFIX)) {
            url = url.substring(Constants.RESOURCE_PREFIX.length());
        }
        return GoerTekConfig.getProfile() + "/" + url;
    }

    /**
     * 解压缩ZIP文件
     * @param zipFile ZIP文件
     * @param destDir 目标路径
     */
    public static void zipDecompress(File zipFile, File destDir) {
        byte[] buffer = new byte[1024];
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) {
            ZipEntry entry = zis.getNextEntry();
            while (entry != null) {
                File file = new File(destDir, entry.getName());
                if (entry.isDirectory()) {
                    file.mkdirs();
                } else {
                    File parent = file.getParentFile();
                    if (!parent.exists()) {
                        parent.mkdirs();
                    }
                    try (FileOutputStream fos = new FileOutputStream(file)) {
                        int len;
                        while ((len = zis.read(buffer)) > 0) {
                            fos.write(buffer, 0, len);
                        }
                    }
                }
                entry = zis.getNextEntry();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值