当前位置:   article > 正文

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

vue elementui 文件上传

 

1.Vue代码

  1. <template>
  2. <div class="app-container">
  3. <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="85px">
  4. <el-form-item label="工号" prop="userCode">
  5. <el-input v-model="queryParams.userCode" placeholder="请输入工号" clearable size="small"
  6. @keyup.enter.native="handleQuery"/>
  7. </el-form-item>
  8. <el-form-item label="姓名" prop="nickName">
  9. <el-input v-model="queryParams.nickName" placeholder="请输入姓名" clearable
  10. size="small" @keyup.enter.native="handleQuery"/>
  11. </el-form-item>
  12. <el-form-item label="部门" prop="deptName">
  13. <el-input v-model="queryParams.deptName" placeholder="请输入部门" clearable
  14. size="small" @keyup.enter.native="handleQuery"/>
  15. </el-form-item>
  16. <el-form-item>
  17. <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
  18. <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
  19. <el-button type="info" icon="el-icon-upload" size="mini" @click="handleImport" v-hasPermi="['riskPredictionData:roster:batchUploadPhoto']">批量上传</el-button>
  20. </el-form-item>
  21. </el-form>
  22. <el-row :gutter="10" class="mb8">
  23. <el-col :span="1.5" v-if="false">
  24. <el-button
  25. type="success"
  26. icon="el-icon-edit"
  27. size="mini"
  28. :disabled="single"
  29. @click="handleUpdate"
  30. v-hasPermi="['riskPredictionData:roster:uploadPhoto']"
  31. >上传照片</el-button>
  32. </el-col>
  33. </el-row>
  34. <el-table ref="reportSupplier" :key="tamptime" :max-height="tableHeight" v-loading="loading" :data="rosterList" >
  35. <el-table-column type="index" width="55" label="序号" align="center" />
  36. <el-table-column label="工号" align="center" prop="userCode" />
  37. <el-table-column label="姓名" align="center" prop="nickName" />
  38. <el-table-column label="部门" align="center" prop="deptName" show-overflow-tooltip />
  39. <el-table-column label="职位" align="center" prop="position" show-overflow-tooltip v-if="false"/>
  40. <el-table-column label="职务" align="center" prop="post" show-overflow-tooltip/>
  41. <el-table-column label="头像" align="center" prop="photo" >
  42. <template slot-scope="scope">
  43. <el-image :src="baseUrl + '/profile/upload/cadrePhoto/' + scope.row.userCode +'.jpg/'" style="height:50px;width:50px" />
  44. </template>
  45. </el-table-column>
  46. <el-table-column label="操作" align="center" >
  47. <template slot-scope="scope">
  48. <el-button
  49. size="mini"
  50. type="text"
  51. icon="el-icon-edit"
  52. @click="handleUpdate(scope.row)"
  53. v-hasPermi="['riskPredictionData:roster:uploadPhoto']"
  54. >上传照片</el-button>
  55. </template>
  56. </el-table-column>
  57. </el-table>
  58. <pagination
  59. v-show="total>0"
  60. :total="total"
  61. :page.sync="queryParams.pageNum"
  62. :limit.sync="queryParams.pageSize"
  63. @pagination="getList"
  64. />
  65. <!-- 花名册入对话框 -->
  66. <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
  67. <el-upload ref="upload" :limit="1" accept=".zip" :headers="upload.headers"
  68. :action="upload.url + '?updateSupport=' + upload.updateSupport"
  69. :disabled="upload.isUploading" :on-progress="handleFileUploadProgress"
  70. :on-success="handleFileSuccess" :auto-upload="false" drag >
  71. <i class="el-icon-upload"></i>
  72. <div class="el-upload__text">
  73. 将文件拖到此处,或
  74. <em>点击上传</em>
  75. </div>
  76. <div
  77. class="el-upload__tip"
  78. slot="tip"
  79. >
  80. <!-- <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据 -->
  81. <!-- <el-link
  82. type="info"
  83. style="font-size:12px"
  84. @click="importTemplate"
  85. >下载模板</el-link>-->
  86. </div>
  87. <div
  88. class="el-upload__tip"
  89. style="color:red"
  90. slot="tip"
  91. >提示:仅允许导入“zip”格式文件!</div>
  92. </el-upload>
  93. <div
  94. slot="footer"
  95. class="dialog-footer"
  96. >
  97. <el-button
  98. type="primary"
  99. @click="submitFileForm"
  100. >确 定</el-button>
  101. <el-button @click="upload.open = false">取 消</el-button>
  102. </div>
  103. </el-dialog>
  104. <!-- 添加或修改成员照对话框 -->
  105. <el-dialog :title="title" :visible.sync="open" width="500px" v-dialog-drag :close-on-click-modal="false">
  106. <el-form ref="form" :model="form" :rules="rules" label-width="95px">
  107. <el-form-item label="工号" prop="userCode">
  108. {{form.userCode}}
  109. </el-form-item>
  110. <!-- <el-form-item label="上传证件照" prop="photo">
  111. <el-upload class="upload-demo"
  112. ref="upload"
  113. accept=".jpg"
  114. :action="uploadPhoto.url+form.userCode"
  115. :headers="uploadPhoto.headers"
  116. :before-upload="handleBefore"
  117. :on-remove="handleRemove"
  118. :on-success="(res, file)=>{handleSuccess( res, file)}"
  119. :show-file-list="false"
  120. >
  121. <el-button slot="trigger" type="primary">选取文件</el-button>
  122. <div slot="tip" class="el-upload__tip">上传文件不能超过10M</div>
  123. </el-upload>
  124. <el-image style="width: 100px; height: 100px" :src="uploadPhoto.imgUrl" fit="fill"></el-image>
  125. </el-form-item>-->
  126. <el-form-item label="上传照片" prop="photo">
  127. <el-upload
  128. ref="uploadPhoto"
  129. class="avatar-uploader"
  130. :key="tamptimeUploadPhoto"
  131. :action="uploadPhoto.url+form.userCode"
  132. :headers="uploadPhoto.headers"
  133. :show-file-list="false"
  134. :on-success="(res, file)=>{handleSuccess( res, file)}"
  135. :before-upload="handleBefore"
  136. :auto-upload="true">
  137. <img v-if="uploadPhoto.isShowPhoto" :src="uploadPhoto.imgUrl" class="avatar">
  138. <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  139. </el-upload>
  140. </el-form-item>
  141. </el-form>
  142. <div slot="footer" class="dialog-footer">
  143. <el-button type="primary" @click="submitForm">确 定</el-button>
  144. <el-button @click="cancel">取 消</el-button>
  145. </div>
  146. </el-dialog>
  147. </div>
  148. </template>
  149. <script>
  150. import {listRoster, getRoster, exportRoster, importTemplate}
  151. from "@/api/hr/riskPrediction/data/roster";
  152. import { getToken } from "@/utils/auth";
  153. import store from "@/store";
  154. import axios from "axios";
  155. export default {
  156. name: "CadrePhoto",
  157. data() {
  158. return {
  159. // 遮罩层
  160. loading: true,
  161. // 选中数组
  162. ids: [],
  163. // 非单个禁用
  164. single: true,
  165. // 非多个禁用
  166. multiple: true,
  167. // 总条数
  168. total: 0,
  169. tableHeight:0,
  170. // 员工风险预判-花名册导入
  171. rosterList: [],
  172. // 弹出层标题
  173. title: "",
  174. // 是否显示弹出层
  175. open: false,
  176. // 查询参数
  177. queryParams: {
  178. pageNum: 1,
  179. pageSize: 10,
  180. userCode: undefined,
  181. nickName: undefined,
  182. deptName: undefined,
  183. post: '部门负责人',
  184. },
  185. // 表单参数
  186. form: {
  187. userCode: undefined,
  188. photo: undefined,
  189. },
  190. // 表单校验
  191. rules: {
  192. userCode: [
  193. { required: true, message: "工号不能为空", trigger: "blur" }
  194. ],
  195. nickName: [
  196. { required: true, message: "姓名不能为空", trigger: "blur" }
  197. ],
  198. },
  199. upload: {
  200. // 是否显示弹出层
  201. open: false,
  202. // 弹出层标题
  203. title: "批量上传",
  204. // 是否禁用上传
  205. isUploading: false,
  206. // 是否更新已经存在的数据
  207. updateSupport: 0,
  208. // 设置上传的请求头部
  209. headers: { Authorization: "Bearer " + getToken() },
  210. // 上传的地址
  211. url: process.env.VUE_APP_BASE_API + "/riskPrediction/data/roster/batchUpload"
  212. },
  213. options: {
  214. img: store.getters.avatar, //裁剪图片的地址
  215. autoCrop: true, // 是否默认生成截图框
  216. autoCropWidth: 200, // 默认生成截图框宽度
  217. autoCropHeight: 200, // 默认生成截图框高度
  218. fixedBox: true // 固定截图框大小 不允许改变
  219. },
  220. uploadPhoto: {
  221. // 设置上传的请求头部
  222. headers: { Authorization: "Bearer " + getToken() },
  223. // 上传的地址
  224. url: process.env.VUE_APP_BASE_API + "/riskPrediction/data/roster/upload/",
  225. imgUrl: '',
  226. isShowPhoto: false,
  227. },
  228. baseUrl: process.env.VUE_APP_BASE_API,
  229. tamptime:new Date().valueOf(),
  230. tamptimeUploadPhoto:new Date().valueOf(),
  231. };
  232. },
  233. created() {
  234. this.getList();
  235. },
  236. mounted() {
  237. // 设置表格最大高度
  238. this.$nextTick(() => {
  239. //屏幕可视化高度-表格上方高度-需求空出高度
  240. this.tableHeight = window.innerHeight - this.$refs.reportSupplier.$el.offsetTop - 140;
  241. });
  242. },
  243. methods: {
  244. /** 导入按钮操作 */
  245. handleImport () {
  246. this.upload.title = "批量导入";
  247. this.upload.open = true;
  248. },
  249. // 文件上传中处理
  250. handleFileUploadProgress (event, file, fileList) {
  251. this.upload.isUploading = true;
  252. },
  253. // 文件上传成功处理
  254. handleFileSuccess (response, file, fileList) {
  255. this.upload.open = false;
  256. this.upload.isUploading = false;
  257. this.$refs.upload.clearFiles();
  258. if(this.strIsEmpty(response.msg)){
  259. this.$message({
  260. message: '请使用模板导入',
  261. type: 'warning'
  262. });
  263. return
  264. }
  265. this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
  266. this.getList();
  267. },
  268. /** 下载模板操作 */
  269. importTemplate () {
  270. importTemplate().then(response => {
  271. this.download(response.msg);
  272. });
  273. },
  274. // 提交上传文件
  275. submitFileForm () {
  276. this.$refs.upload.submit();
  277. },
  278. /** 查询员工风险预判-花名册导入 */
  279. getList() {
  280. this.loading = true;
  281. this.tamptime = new Date().valueOf()
  282. listRoster(this.queryParams).then(response => {
  283. this.rosterList = response.rows;
  284. this.total = response.total;
  285. this.loading = false;
  286. // 数据并不会更新, 随便调用一下页面事件,什么事件都可以,聚焦等都可以,这里使用 element 表格自带的高亮行事件
  287. this.$refs.reportSupplier.setCurrentRow(this.rosterList[0])
  288. });
  289. },
  290. /** 搜索按钮操作 */
  291. handleQuery() {
  292. this.queryParams.pageNum = 1;
  293. this.getList();
  294. },
  295. /** 重置按钮操作 */
  296. resetQuery() {
  297. this.resetForm("queryForm");
  298. this.handleQuery();
  299. },
  300. /** 修改按钮操作 */
  301. handleUpdate(row) {
  302. this.reset();
  303. const userCode = row.userCode
  304. const _that = this
  305. getRoster(userCode).then(response => {
  306. this.form = response.data;
  307. if(this.form.userCode){
  308. this.uploadPhoto.imgUrl = process.env.VUE_APP_BASE_API + "/profile/upload/cadrePhoto/" + this.form.userCode +'.jpg'
  309. axios.get(_that.uploadPhoto.imgUrl)
  310. .then(function (response) {
  311. if(response.status == 200){
  312. _that.uploadPhoto.isShowPhoto = true;
  313. }
  314. })
  315. .catch(function (error) {
  316. // 处理请求失败的结果
  317. });
  318. /*getImgUrl(this.uploadPhoto.imgUrl).then(response=>{
  319. if(response.status == 200){
  320. uploadPhoto.isShowPhoto = true;
  321. }
  322. }).catch(error => {
  323. })*/
  324. }
  325. this.open = true;
  326. this.title = "修改照片";
  327. });
  328. },
  329. // 取消按钮
  330. cancel() {
  331. this.open = false;
  332. this.getList()
  333. },
  334. /** 提交按钮 */
  335. submitForm: function() {
  336. this.open = false;
  337. this.getList()
  338. //this.$refs.uploadPhoto.submit();
  339. },
  340. reset(){
  341. this.form = {
  342. userCode : undefined,
  343. photo: undefined,
  344. },
  345. this.uploadPhoto = {
  346. // 设置上传的请求头部
  347. headers: { Authorization: "Bearer " + getToken() },
  348. // 上传的地址
  349. url: process.env.VUE_APP_BASE_API + "/riskPrediction/data/roster/upload/",
  350. imgUrl: '',
  351. isShowPhoto: false,
  352. }
  353. },
  354. handleBefore (file) {
  355. var fileExtension = file.name.substring(file.name.lastIndexOf('.') + 1);
  356. if (["jpg"].indexOf(fileExtension) == -1) {
  357. //文件类型
  358. this.$message({
  359. message: "不支持上传." + fileExtension+ "类型的附件",
  360. type: 'warning'
  361. })
  362. return false;
  363. }
  364. if ( file.size > 10485760) {
  365. //文件不能大于10M
  366. this.$message({
  367. message: "上传附件不能大于10M",
  368. type: 'warning'
  369. })
  370. return false;
  371. }
  372. },
  373. handleRemove(file, fileList) {
  374. },
  375. handleSuccess(res, file){
  376. if (res.code === 200) {
  377. this.uploadPhoto.imgUrl = res.url
  378. this.form.photo =file.fileName
  379. this.uploadPhoto.isShowPhoto = true;
  380. this.tamptimeUploadPhoto = new Date().valueOf()
  381. }else{
  382. this.uploadPhoto.imgUrl = null
  383. this.form.photo = null
  384. }
  385. },
  386. getImgUrl(){
  387. return this.uploadPhoto.imgUrl
  388. }
  389. }
  390. };
  391. </script>
  392. <style>
  393. .avatar-uploader .el-upload {
  394. border: 1px dashed #d9d9d9;
  395. border-radius: 6px;
  396. cursor: pointer;
  397. position: relative;
  398. overflow: hidden;
  399. }
  400. .avatar-uploader .el-upload:hover {
  401. border-color: #409EFF;
  402. }
  403. .avatar-uploader-icon {
  404. font-size: 28px;
  405. color: #8c939d;
  406. width: 178px;
  407. height: 178px;
  408. line-height: 178px;
  409. text-align: center;
  410. }
  411. .avatar {
  412. width: 178px;
  413. height: 178px;
  414. display: block;
  415. }
  416. </style>

2.roster.js代码

  1. import request from '@/utils/request'
  2. // 查询员工风险预判-花名册导入+员工基础信息列表
  3. export function listRoster(query) {
  4. return request({
  5. url: '/riskPrediction/data/roster/list',
  6. method: 'get',
  7. params: query
  8. })
  9. }
  10. // 查询员工风险预判-花名册导入+员工基础信息详细
  11. export function getRoster(userCode) {
  12. return request({
  13. url: '/riskPrediction/data/roster/' + userCode,
  14. method: 'get'
  15. })
  16. }
  17. // 导出员工风险预判-花名册导入+员工基础信息
  18. export function exportRoster(query) {
  19. return request({
  20. url: '/riskPrediction/data/roster/export',
  21. method: 'get',
  22. params: query
  23. })
  24. }
  25. // 下载模板
  26. export function importTemplate() {
  27. return request({
  28. url: '/riskPrediction/data/roster/importTemplate',
  29. method: 'get'
  30. })
  31. }

3.auth.js代码

  1. import Cookies from 'js-cookie'
  2. import router from './../router'
  3. import store from '@/store'
  4. const TokenKey = 'Admin-Token'
  5. const ssoToken = 'sso_session';
  6. export function getAuthHeader() {
  7. let header = {};
  8. if (getToken()) {
  9. header['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  10. }
  11. let route = router.currentRoute;
  12. if (route && route.meta && route.meta.roleIds) {
  13. header['routerRoleIds'] = route.meta.roleIds // 让每个请求携带权限表示
  14. }
  15. return header;
  16. }
  17. export function getRedirectRoutePath(toRoute) {
  18. if(!toRoute) {
  19. return {path:"/"};
  20. }
  21. let toPath = toRoute.path;
  22. const permissionRoutes = store.getters && store.getters.permission_routes
  23. if (!permissionRoutes || permissionRoutes.length < 1) {
  24. return {path:"/"};
  25. }
  26. if (toPath == "/") {
  27. let permissionRootPaths = permissionRoutes.filter(route=>{
  28. if (route.path == "" && route.children
  29. && route.children.length > 0 ) {
  30. let t = route.children[0];
  31. return t.path == "/bgBoard"
  32. }
  33. return false;
  34. })
  35. if (permissionRootPaths.length > 0) {
  36. let t = permissionRootPaths[0].children[0];
  37. return {path:t.path};
  38. }
  39. return {path:"/index"};
  40. }
  41. return toRoute;
  42. }
  43. export function getToken() {
  44. return Cookies.get(TokenKey)
  45. }
  46. export function setToken(token) {
  47. return Cookies.set(TokenKey, token)
  48. }
  49. export function removeToken() {
  50. return Cookies.remove(TokenKey)
  51. }
  52. export function getSSOToken() {
  53. return Cookies.get(ssoToken)
  54. }
  55. export function setSSOToken(token) {
  56. return Cookies.set(ssoToken, token)
  57. }
  58. export function removeSSOToken() {
  59. return Cookies.remove(ssoToken)
  60. }

4.后端代码

  1. package com.goertek.riskPrediction.data.controller;
  2. import com.goertek.framework.aspectj.lang.enums.BusinessType;
  3. import com.goertek.framework.config.GoerTekConfig;
  4. import com.goertek.framework.config.ServerConfig;
  5. import com.goertek.framework.utils.poi.ExcelUtil;
  6. import com.goertek.framework.web.controller.BaseController;
  7. import com.goertek.framework.web.domain.AjaxResult;
  8. import com.goertek.framework.web.page.TableDataInfo;
  9. import com.goertek.hrLog.HrLog;
  10. import com.goertek.hrUtils.CadreFileUploadUtils;
  11. import com.goertek.riskPrediction.data.domain.HrRiskPredictionImportRoster;
  12. import com.goertek.riskPrediction.data.service.IHrRiskPredictionImportRosterService;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.security.access.prepost.PreAuthorize;
  15. import org.springframework.web.bind.annotation.*;
  16. import org.springframework.web.multipart.MultipartFile;
  17. import java.io.File;
  18. import java.util.List;
  19. /**
  20. * 员工风险预判-花名册导入Controller
  21. *
  22. * @author xx
  23. * @date 2021-08-30
  24. */
  25. @RestController
  26. @RequestMapping("/riskPrediction/data/roster")
  27. public class HrRiskPredictionImportRosterControllerTest extends BaseController
  28. {
  29. @Autowired
  30. private ServerConfig serverConfig;
  31. /**
  32. * 照片上传请求
  33. */
  34. @HrLog(title = "照片上传", businessType = BusinessType.IMPORT)
  35. @PostMapping("/upload/{userCode}")
  36. public AjaxResult uploadFile(MultipartFile file,@PathVariable("userCode") String userCode) throws Exception
  37. {
  38. try
  39. {
  40. String originalFilename = userCode + ".jpg";
  41. // 上传文件路径
  42. String filePath = GoerTekConfig.getUploadPath()+ "/cadrePhoto";;
  43. // 上传并返回新文件名称
  44. String fileName = CadreFileUploadUtils.upload(filePath, file, originalFilename);
  45. String url = serverConfig.getUrl() + fileName;
  46. AjaxResult ajax = AjaxResult.success();
  47. ajax.put("fileName", fileName);
  48. ajax.put("url", url);
  49. ajax.put("realName", file.getOriginalFilename());
  50. return ajax;
  51. }
  52. catch (Exception e)
  53. {
  54. return AjaxResult.error(e.getMessage());
  55. }
  56. }
  57. @HrLog(title = "批量导入", businessType = BusinessType.IMPORT)
  58. @PostMapping("/batchUpload")
  59. public AjaxResult batchUpload(MultipartFile file, boolean updateSupport) throws Exception
  60. {
  61. try
  62. {
  63. String originalFilename = file.getOriginalFilename();
  64. // 上传文件路径
  65. String filePath = GoerTekConfig.getUploadPath()+ "/cadrePhoto";;
  66. // 上传并返回新文件名称
  67. String fileName = CadreFileUploadUtils.upload(filePath, file, originalFilename);
  68. String url = serverConfig.getUrl() + fileName;
  69. AjaxResult ajax = AjaxResult.success();
  70. ajax.put("fileName", fileName);
  71. ajax.put("url", url);
  72. ajax.put("realName", file.getOriginalFilename());
  73. //解压
  74. File zipFile = new File(filePath+"/"+originalFilename);
  75. File destDir = new File(filePath);
  76. CadreFileUploadUtils.zipDecompress(zipFile,destDir);
  77. return ajax;
  78. }
  79. catch (Exception e)
  80. {
  81. return AjaxResult.error(e.getMessage());
  82. }
  83. }
  84. }
5.CadreFileUploadUtils.java
  1. package com.goertek.hrUtils;
  2. import com.goertek.framework.config.GoerTekConfig;
  3. import com.goertek.framework.constant.Constants;
  4. import com.goertek.framework.exception.file.FileNameLengthLimitExceededException;
  5. import com.goertek.framework.exception.file.FileSizeLimitExceededException;
  6. import com.goertek.framework.exception.file.InvalidExtensionException;
  7. import com.goertek.framework.utils.DateUtils;
  8. import com.goertek.framework.utils.StringUtils;
  9. import com.goertek.framework.utils.file.MimeTypeUtils;
  10. import com.goertek.framework.utils.security.Md5Utils;
  11. import org.apache.commons.io.FilenameUtils;
  12. import org.springframework.web.multipart.MultipartFile;
  13. import java.io.File;
  14. import java.io.FileInputStream;
  15. import java.io.FileOutputStream;
  16. import java.io.IOException;
  17. import java.util.zip.ZipEntry;
  18. import java.util.zip.ZipInputStream;
  19. /**
  20. * 文件上传工具类
  21. *
  22. * @author admin
  23. */
  24. public class CadreFileUploadUtils {
  25. /**
  26. * 默认的文件名最大长度 100
  27. */
  28. public static final int DEFAULT_FILE_NAME_LENGTH = 100;
  29. /**
  30. * 默认上传的地址
  31. */
  32. private static String defaultBaseDir = GoerTekConfig.getProfile();
  33. private static int counter = 0;
  34. public static void setDefaultBaseDir(String defaultBaseDir) {
  35. CadreFileUploadUtils.defaultBaseDir = defaultBaseDir;
  36. }
  37. public static String getDefaultBaseDir() {
  38. return defaultBaseDir;
  39. }
  40. /**
  41. * 以默认配置进行文件上传
  42. *
  43. * @param file 上传的文件
  44. * @return 文件名称
  45. * @throws Exception
  46. */
  47. public static final String upload(MultipartFile file, String fileName) throws IOException {
  48. try {
  49. return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, fileName);
  50. } catch (Exception e) {
  51. throw new IOException(e.getMessage(), e);
  52. }
  53. }
  54. /**
  55. * 根据文件路径上传
  56. *
  57. * @param baseDir 相对应用的基目录
  58. * @param file 上传的文件
  59. * @return 文件名称
  60. * @throws IOException
  61. */
  62. public static final String upload(String baseDir, MultipartFile file, String fileName) throws IOException {
  63. try {
  64. return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, fileName);
  65. } catch (Exception e) {
  66. throw new IOException(e.getMessage(), e);
  67. }
  68. }
  69. /**
  70. * 根据文件路径上传
  71. *
  72. * @param baseDir 相对应用的基目录
  73. * @param file 上传的文件
  74. * @return 文件名称
  75. * @throws IOException
  76. */
  77. public static final String uploadWithoutDate(String baseDir, MultipartFile file) throws IOException {
  78. try {
  79. int fileNamelength = file.getOriginalFilename().length();
  80. if (fileNamelength > com.goertek.framework.utils.file.FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
  81. throw new FileNameLengthLimitExceededException(com.goertek.framework.utils.file.FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
  82. }
  83. // assertAllowed(file, allowedExtension);
  84. String fileName = file.getOriginalFilename();
  85. File desc = getAbsoluteFile(baseDir, fileName);
  86. file.transferTo(desc);
  87. String pathFileName = getPathFileName(baseDir, fileName);
  88. return pathFileName;
  89. } catch (Exception e) {
  90. throw new IOException(e.getMessage(), e);
  91. }
  92. }
  93. /**
  94. * 文件上传
  95. *
  96. * @param baseDir 相对应用的基目录
  97. * @param file 上传的文件
  98. * @return 返回上传成功的文件名
  99. * @throws FileSizeLimitExceededException 如果超出最大大小
  100. * @throws FileNameLengthLimitExceededException 文件名太长
  101. * @throws IOException 比如读写文件出错时
  102. * @throws InvalidExtensionException 文件校验异常
  103. */
  104. public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension, String fileName)
  105. throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
  106. InvalidExtensionException {
  107. int fileNamelength = file.getOriginalFilename().length();
  108. if (fileNamelength > CadreFileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
  109. throw new FileNameLengthLimitExceededException(CadreFileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
  110. }
  111. //String fileName = extractFilename(file);
  112. //String fileName = file.getOriginalFilename();
  113. File desc = getAbsoluteFile(baseDir, fileName);
  114. file.transferTo(desc);
  115. String pathFileName = getPathFileName(baseDir, fileName);
  116. return pathFileName;
  117. }
  118. /**
  119. * 编码文件名
  120. */
  121. public static final String extractFilename(MultipartFile file) {
  122. String fileName = file.getOriginalFilename();
  123. String extension = getExtension(file);
  124. fileName = DateUtils.datePath() + "/" + encodingFilename(fileName) + "." + extension;
  125. return fileName;
  126. }
  127. private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
  128. File desc = new File(uploadDir + File.separator + fileName);
  129. if (!desc.getParentFile().exists()) {
  130. desc.getParentFile().mkdirs();
  131. }
  132. if (!desc.exists()) {
  133. desc.createNewFile();
  134. }else{
  135. desc.createNewFile();
  136. }
  137. return desc;
  138. }
  139. private static final String getPathFileName(String uploadDir, String fileName) throws IOException {
  140. int dirLastIndex = GoerTekConfig.getProfile().length() + 1;
  141. String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
  142. String pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
  143. return pathFileName;
  144. }
  145. /**
  146. * 编码文件名
  147. */
  148. private static final String encodingFilename(String fileName) {
  149. fileName = fileName.replace("_", " ");
  150. fileName = Md5Utils.hash(fileName + System.nanoTime() + counter++);
  151. return fileName;
  152. }
  153. /**
  154. * 文件大小校验
  155. *
  156. * @param file 上传的文件
  157. * @return
  158. * @throws FileSizeLimitExceededException 如果超出最大大小
  159. * @throws InvalidExtensionException
  160. */
  161. public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
  162. throws FileSizeLimitExceededException, InvalidExtensionException {
  163. long size = file.getSize();
  164. String fileName = file.getOriginalFilename();
  165. String extension = getExtension(file);
  166. if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
  167. if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) {
  168. throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
  169. fileName);
  170. } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) {
  171. throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
  172. fileName);
  173. } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) {
  174. throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
  175. fileName);
  176. } else {
  177. throw new InvalidExtensionException(allowedExtension, extension, fileName);
  178. }
  179. }
  180. }
  181. /**
  182. * 判断MIME类型是否是允许的MIME类型
  183. *
  184. * @param extension
  185. * @param allowedExtension
  186. * @return
  187. */
  188. public static final boolean isAllowedExtension(String extension, String[] allowedExtension) {
  189. for (String str : allowedExtension) {
  190. if (str.equalsIgnoreCase(extension)) {
  191. return true;
  192. }
  193. }
  194. return false;
  195. }
  196. /**
  197. * 获取文件名的后缀
  198. *
  199. * @param file 表单文件
  200. * @return 后缀名
  201. */
  202. public static final String getExtension(MultipartFile file) {
  203. String extension = FilenameUtils.getExtension(file.getOriginalFilename());
  204. if (StringUtils.isEmpty(extension)) {
  205. extension = MimeTypeUtils.getExtension(file.getContentType());
  206. }
  207. return extension;
  208. }
  209. public static String getUploadFile(String url) {
  210. if (!url.startsWith("/")) {
  211. url = "/" + url;
  212. }
  213. if (url.startsWith(Constants.RESOURCE_PREFIX)) {
  214. url = url.substring(Constants.RESOURCE_PREFIX.length());
  215. }
  216. return GoerTekConfig.getProfile() + "/" + url;
  217. }
  218. /**
  219. * 解压缩ZIP文件
  220. * @param zipFile ZIP文件
  221. * @param destDir 目标路径
  222. */
  223. public static void zipDecompress(File zipFile, File destDir) {
  224. byte[] buffer = new byte[1024];
  225. try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) {
  226. ZipEntry entry = zis.getNextEntry();
  227. while (entry != null) {
  228. File file = new File(destDir, entry.getName());
  229. if (entry.isDirectory()) {
  230. file.mkdirs();
  231. } else {
  232. File parent = file.getParentFile();
  233. if (!parent.exists()) {
  234. parent.mkdirs();
  235. }
  236. try (FileOutputStream fos = new FileOutputStream(file)) {
  237. int len;
  238. while ((len = zis.read(buffer)) > 0) {
  239. fos.write(buffer, 0, len);
  240. }
  241. }
  242. }
  243. entry = zis.getNextEntry();
  244. }
  245. } catch (IOException e) {
  246. e.printStackTrace();
  247. }
  248. }
  249. }

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/805641
推荐阅读
  

闽ICP备14008679号