index.vue 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. <template>
  2. <div class="upload-file">
  3. <el-upload
  4. multiple
  5. drag
  6. :action="uploadFileUrl"
  7. :before-upload="handleBeforeUpload"
  8. :on-error="uploadedSuccessfully"
  9. :on-success="handleUploadSuccess"
  10. :file-list="fileList"
  11. :limit="limit"
  12. :accept="accept"
  13. :http-request="uploadFile"
  14. :show-file-list="true"
  15. :on-remove="handleDelete"
  16. :on-exceed="handleExceed"
  17. :on-preview="onPreview"
  18. :headers="headers" class="upload-file-uploader" ref="fileUpload">
  19. <i class="el-icon-upload"></i>
  20. <!-- 上传按钮 -->
  21. <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
  22. <!-- <el-button size="mini" type="primary">{{ btnName }}</el-button> -->
  23. <!-- 上传提示 -->
  24. <div class="el-upload__tip" slot="tip" v-if="showTip">
  25. 文件<template v-if="fileSize">大小不超过<b style="color: #f56c6c">{{ fileSize }}MB</b></template>
  26. <template v-if="fileType"> 格式为<b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
  27. 的文件
  28. </div>
  29. </el-upload>
  30. <!-- 文件列表 -->
  31. <!-- <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
  32. <li :key="file.url" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
  33. <el-link :href="getFileUrl(file)" :underline="false" target="_blank">
  34. <span class="el-icon-document"> {{ getFileName(file) }} </span>
  35. </el-link>
  36. <div class="ele-upload-list__item-content-action">
  37. <el-link :underline="false" @click="handleDelete(index)" type="danger">删除</el-link>
  38. </div>
  39. </li>
  40. </transition-group> -->
  41. </div>
  42. </template>
  43. <script>
  44. import { getToken } from "@/utils/auth";
  45. import { upload } from "@/api/system/public";
  46. export default {
  47. name: "K-FileUpload",
  48. props: {
  49. // 值
  50. value: [String, Object, Array],
  51. defaultValue: [String, Object, Array],
  52. // 数量限制
  53. limit: {
  54. type: Number,
  55. default: 5,
  56. },
  57. // 大小限制(MB)
  58. fileSize: {
  59. type: Number,
  60. default: 20,
  61. },
  62. // 文件类型, 例如['png', 'jpg', 'jpeg']
  63. fileType: {
  64. type: Array,
  65. default: () => ["pdf", "jpg", "png", "bmp","doc","docx","ppt","pptx","xls","xlsx","zip","rar","7z"],
  66. },
  67. // 是否显示提示
  68. isShowTip: {
  69. type: Boolean,
  70. default: true
  71. },
  72. btnName: {
  73. type: String,
  74. default: "选取文件",
  75. },
  76. },
  77. data() {
  78. return {
  79. number: 0,
  80. uploadList: [],
  81. uploadFileUrl: process.env.VUE_APP_BASE_API + "/file/upload", // 上传文件服务器地址
  82. headers: {
  83. Authorization: "Bearer " + getToken(),
  84. },
  85. fileList: [],
  86. fileValueList:[],
  87. accept: ".pdf,.jpg,.png,.bmp",
  88. };
  89. },
  90. watch: {
  91. defaultValue:{
  92. handler(val) {
  93. if (val) {
  94. let temp = 1;
  95. // this.fileList=val;
  96. // 首先将值转为数组
  97. const list = Array.isArray(val) ? val : this.value.split(',');
  98. console.log("watch fileList", list)
  99. if(list.length>this.limit)
  100. {
  101. this.handleExceed();
  102. return;
  103. }
  104. // 然后将数组转为对象数组
  105. this.fileList = list.map(item => {
  106. if (typeof item === "string") {
  107. // console.log("watch fileList item", item)
  108. let itemObj = JSON.parse(item);
  109. // console.log("watch fileList itemObj", itemObj)
  110. if ('name' in itemObj && 'url' in itemObj) {
  111. item=itemObj
  112. }
  113. else {
  114. item = { name: item, url: item };
  115. }
  116. }
  117. item.uid = item.uid || new Date().getTime() + temp++;
  118. return item;
  119. });
  120. this.fileValueList=[...this.fileList];
  121. this.$emit("input", this.listToTagObj(this.fileValueList));
  122. } else {
  123. this.fileList = [];
  124. this.fileValueList=[];
  125. return [];
  126. }
  127. },
  128. deep: true,
  129. immediate: true
  130. },
  131. value: {
  132. handler(val) {
  133. },
  134. deep: true,
  135. immediate: true
  136. }
  137. },
  138. computed: {
  139. // 是否显示提示
  140. showTip() {
  141. return this.isShowTip && (this.fileType || this.fileSize);
  142. },
  143. },
  144. methods: {
  145. // 上传前校检格式和大小
  146. handleBeforeUpload(file) {
  147. // 校检文件类型
  148. if (this.fileType) {
  149. const fileName = file.name.split('.');
  150. const fileExt = fileName[fileName.length - 1];
  151. const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
  152. if (!isTypeOk) {
  153. this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
  154. return false;
  155. }
  156. }
  157. // 校检文件大小
  158. if (this.fileSize) {
  159. const isLt = file.size / 1024 / 1024 < this.fileSize;
  160. if (!isLt) {
  161. this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
  162. return false;
  163. }
  164. }
  165. if(this.fileList.findIndex(x=>x.name==file.name)>-1)
  166. {
  167. this.$modal.msgError(`不能上传相同名称的文件或图片!`);
  168. return false;
  169. }
  170. this.$modal.loading("正在上传文件,请稍候...");
  171. this.number++;
  172. return true;
  173. },
  174. // 文件个数超出
  175. handleExceed() {
  176. this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
  177. },
  178. // 上传失败
  179. handleUploadError(err) {
  180. this.$modal.msgError("上传文件失败,请重试");
  181. this.$modal.closeLoading()
  182. },
  183. // 上传成功回调
  184. handleUploadSuccess(res, file,fileList) {
  185. console.log("handleUploadSuccess", res, file, fileList);
  186. this.fileList=fileList;
  187. this.$emit("input", this.listToTagObj(this.fileValueList));
  188. },
  189. // 删除文件
  190. handleDelete(item) {
  191. if (item && item.status === "success") {
  192. console.log("handleDelete index",item)
  193. //this.fileList.splice(item, 1);
  194. // console.log("handleDelete",item,this.fileValueList)
  195. let index = this.fileValueList.findIndex(x=>x.name==item.name);
  196. // console.log("handleDelete",index,this.fileValueList)
  197. if(index>-1)
  198. {
  199. this.fileValueList.splice(index, 1);
  200. }
  201. //this.fileValueList.splice(item, 1);
  202. console.log("handleDelete deleted",this.fileValueList)
  203. this.$emit("input", this.listToTagObj(this.fileValueList));
  204. }
  205. },
  206. // 上传失败结束处理 必须调用,否则失败文件也会显示
  207. uploadedSuccessfully(err,file,fileList) {
  208. },
  209. // 获取文件名称
  210. getFileName(name) {
  211. // 将字符串的 JSON 转换为对象
  212. const fileObj = JSON.parse(name);
  213. // 返回 name 属性
  214. return fileObj.name;
  215. },
  216. // 获取文件url
  217. getFileUrl(name) {
  218. // 将字符串的 JSON 转换为对象
  219. const fileObj = JSON.parse(name);
  220. // 返回 name 属性
  221. return fileObj.url;
  222. },
  223. //自定义上传方式(自带的成功回调及失败回调会失效)
  224. uploadFile(fileObj) {
  225. let formData = new FormData();
  226. formData.append('file', fileObj.file);
  227. console.log("this.fileValueList.length",this.fileValueList.length)
  228. if (this.fileValueList.length<=this.limit){
  229. upload(formData, 'image').then(res => {
  230. /*上传成功*/
  231. this.$modal.closeLoading();
  232. //let imgUrl = process.env.VUE_APP_BASE_API + res.data.url;
  233. let arr = [];
  234. arr.push({ name: res.data.realName, url: res.data.url });
  235. this.fileValueList = this.fileValueList.concat(arr);
  236. // console.log("uploadFile", this.fileList)
  237. fileObj.onSuccess();
  238. }).catch(err => {
  239. /*上传失败*/
  240. this.$modal.closeLoading();
  241. fileObj.onError()
  242. })
  243. }
  244. },
  245. // 对象转成指定字符串分隔
  246. listToString(list, separator) {
  247. let strs = "";
  248. separator = separator || ",";
  249. for (let i in list) {
  250. strs += list[i].url + separator;
  251. }
  252. return strs != '' ? strs.substring(0, strs.length - 1) : '';
  253. },
  254. listToTagObj(list) {
  255. let tempArry=[];
  256. for (let i in list) {
  257. // console.log("listToString2 i",i);
  258. tempArry.push(JSON.stringify( {url:list[i].url,name:list[i].name}));
  259. }
  260. console.log("listToString2",tempArry);
  261. return tempArry;
  262. },
  263. onPreview(file) {
  264. console.log(file);
  265. var name = file.name;
  266. let index = this.fileValueList.findIndex(x=>x.name==file.name);
  267. this.fileValueList[index]
  268. var url = this.fileValueList[index].url;
  269. if(process.env.VUE_APP_BASE_API!=='/')
  270. {
  271. url=process.env.VUE_APP_BASE_API+this.fileValueList[index].url;
  272. }
  273. // console.log("process.env.VUE_APP_BASE_API",process.env.VUE_APP_BASE_API,process)
  274. // console.log("process.env.VUE_APP_BASE_API url",url)
  275. const a = document.createElement("a");
  276. a.setAttribute("download", name);
  277. a.setAttribute("target", "_blank");
  278. a.setAttribute("href", url);
  279. a.click();
  280. },
  281. clearFiles(){
  282. this.$refs["fileUpload"].clearFiles();
  283. this.fileList = [];
  284. this.fileValueList = [];
  285. },
  286. }
  287. };
  288. </script>
  289. <style scoped lang="scss">
  290. .upload-file-uploader {
  291. margin-bottom: 5px;
  292. }
  293. .el-upload-list__item {
  294. transition: none !important;
  295. }
  296. .upload-file-list .el-upload-list__item {
  297. border: 1px solid #e4e7ed;
  298. line-height: 2;
  299. margin-bottom: 10px;
  300. position: relative;
  301. }
  302. .upload-file-list .ele-upload-list__item-content {
  303. display: flex;
  304. justify-content: space-between;
  305. align-items: center;
  306. color: inherit;
  307. }
  308. .ele-upload-list__item-content-action .el-link {
  309. margin-right: 10px;
  310. }
  311. </style>