index.vue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. <template>
  2. <div class="cl-upload__wrap">
  3. <div
  4. class="cl-upload"
  5. :class="[
  6. `cl-upload--${listType}`,
  7. {
  8. 'is-multiple': multiple,
  9. 'is-drag': drag
  10. }
  11. ]"
  12. >
  13. <el-input class="cl-upload__hidden" type="hidden" v-model="value"></el-input>
  14. <el-upload
  15. :action="action"
  16. :accept="_accept"
  17. :multiple="multiple"
  18. :limit="limit"
  19. :data="data"
  20. :name="_name"
  21. :drag="drag"
  22. :list-type="listType"
  23. :file-list="fileList"
  24. :show-file-list="_showFileList"
  25. :auto-upload="autoUpload"
  26. :disabled="disabled"
  27. :headers="{
  28. Authorization: token,
  29. ...headers
  30. }"
  31. :http-request="action ? undefined : httpRequest"
  32. :on-remove="_onRemove"
  33. :on-preview="_onPreview"
  34. :on-success="_onSuccess"
  35. :on-error="onError"
  36. :on-progress="onProgress"
  37. :on-change="onChange"
  38. :on-exceed="onExceed"
  39. :before-upload="_beforeUpload"
  40. :before-remove="beforeRemove"
  41. :style="_style"
  42. v-loading="_loading"
  43. >
  44. <slot>
  45. <!-- picture-card -->
  46. <template v-if="listType == 'picture-card'">
  47. <i :class="['cl-upload__icon', _icon]"></i>
  48. <span class="cl-upload__text" v-if="_text">{{ _text }}</span>
  49. </template>
  50. <!-- text -->
  51. <template v-else-if="listType == 'text'">
  52. <el-button size="mini" type="primary" :loading="loading"
  53. >点击上传</el-button
  54. >
  55. </template>
  56. <template v-else>
  57. <div class="cl-upload__cover" v-if="_urls[0]">
  58. <img v-if="_urls[0].type == 'image'" :src="_urls[0].url" />
  59. <span v-else>{{ _urls[0].name }}</span>
  60. </div>
  61. <template v-else>
  62. <i :class="['cl-upload__icon', _icon]"></i>
  63. <span class="cl-upload__text" v-if="_text">{{ _text }}</span>
  64. </template>
  65. </template>
  66. </slot>
  67. </el-upload>
  68. </div>
  69. <cl-dialog
  70. title="图片预览"
  71. :visible.sync="preview.visible"
  72. :props="{
  73. width: previewWidth
  74. }"
  75. >
  76. <img width="100%" :src="preview.url" alt="" />
  77. </cl-dialog>
  78. </div>
  79. </template>
  80. <script>
  81. import { mapGetters } from "vuex";
  82. import path from "path";
  83. import { cloneDeep, last, isArray, isNumber, isEmpty } from "cl-admin/utils";
  84. import { v4 as uuidv4 } from "uuid";
  85. import { isDev } from "@/config/env";
  86. export default {
  87. name: "cl-upload",
  88. props: {
  89. value: [Array, String],
  90. // 尺寸
  91. size: [Array, String, Number],
  92. // 显示图标
  93. icon: String,
  94. // 显示文案
  95. text: String,
  96. // 是否以 uuid 重命名
  97. rename: {
  98. type: Boolean,
  99. default: true
  100. },
  101. // 最大允许上传文件大小(MB)
  102. limitSize: {
  103. type: Number,
  104. default: 2
  105. },
  106. // 预览图片的宽度
  107. previewWidth: {
  108. type: String,
  109. default: "500px"
  110. },
  111. // 上传的地址
  112. action: {
  113. type: String,
  114. default: ""
  115. },
  116. // 设置上传的请求头部
  117. headers: Object,
  118. // 是否多选
  119. multiple: Boolean,
  120. // 上传时附带的额外参数
  121. data: Object,
  122. // 上传的文件字段名
  123. name: String,
  124. // 支持发送 cookie 凭证信息
  125. withCredentials: Boolean,
  126. // 是否显示已上传文件列表
  127. showFileList: {
  128. type: Boolean,
  129. default: undefined
  130. },
  131. // 是否拖拽
  132. drag: Boolean,
  133. // 上传的文件类型
  134. accept: String,
  135. // 文件列表的类型
  136. listType: {
  137. type: String,
  138. default: "default"
  139. },
  140. // 是否自带上传
  141. autoUpload: {
  142. type: Boolean,
  143. default: true
  144. },
  145. // 是否禁用
  146. disabled: Boolean,
  147. // 最大允许上传个数
  148. limit: Number,
  149. // 文件列表移除文件时的钩子
  150. onRemove: Function,
  151. // 点击文件列表中已上传的文件时的钩子
  152. onPreview: Function,
  153. // 文件上传成功时的钩子
  154. onSuccess: Function,
  155. // 文件上传失败时的钩子
  156. onError: Function,
  157. // 文件上传时的钩子
  158. onProgress: Function,
  159. // 文件状态改变时的钩子
  160. onChange: Function,
  161. // 文件超出个数限制时的钩子
  162. onExceed: Function,
  163. // 上传文件之前的钩子
  164. beforeUpload: Function,
  165. // 删除文件之前的钩子
  166. beforeRemove: Function
  167. },
  168. data() {
  169. return {
  170. fileList: [],
  171. urls: [],
  172. loading: false,
  173. preview: {
  174. visible: false,
  175. url: null
  176. }
  177. };
  178. },
  179. computed: {
  180. ...mapGetters(["token", "modules", "upload"]),
  181. conf() {
  182. return this.modules.upload.options;
  183. },
  184. _size() {
  185. return this.size || this.conf.size || "128px";
  186. },
  187. _icon() {
  188. return this.icon || this.conf.icon || "el-icon-upload";
  189. },
  190. _text() {
  191. return this.text || this.conf.text || "选择文件";
  192. },
  193. _accept() {
  194. let d = this.accept || this.conf.accept;
  195. switch (this.listType) {
  196. case "picture-card":
  197. return d || "image/*";
  198. default:
  199. return d;
  200. }
  201. },
  202. _name() {
  203. return this.name || this.conf.name || "file";
  204. },
  205. _limitSize() {
  206. return this.limitSize || this.conf.limitSize || 2;
  207. },
  208. _showFileList() {
  209. let f = null;
  210. switch (this.listType) {
  211. case "picture-card":
  212. case "text":
  213. f = true;
  214. break;
  215. default:
  216. f = false;
  217. break;
  218. }
  219. return this.showFileList === undefined ? f : this.showFileList;
  220. },
  221. _loading() {
  222. return this.listType == "default" ? this.loading : false;
  223. },
  224. _urls() {
  225. const format = {
  226. image: ["bmp", "jpg", "jpeg", "png", "tif", "gif", "svg"]
  227. };
  228. return this.urls
  229. .filter((e) => Boolean(e.url))
  230. .map((e) => {
  231. let arr = e.url.split(".");
  232. let suf = last(arr);
  233. e.type = format.image.includes(suf) ? "image" : null;
  234. return e;
  235. });
  236. },
  237. _style() {
  238. let arr = [];
  239. if (isArray(this._size)) {
  240. arr = this._size;
  241. } else {
  242. arr = [this._size, this._size];
  243. }
  244. const [height, width] = arr.map((e) => (isNumber(e) ? `${e}px` : e));
  245. if (this.listType == "default" && !this.drag) {
  246. return {
  247. height,
  248. width
  249. };
  250. } else {
  251. return {};
  252. }
  253. }
  254. },
  255. watch: {
  256. value: {
  257. immediate: true,
  258. handler: "parseValue"
  259. }
  260. },
  261. methods: {
  262. // 解析参数
  263. parseValue(value) {
  264. let list = [];
  265. if (this.multiple) {
  266. if (value instanceof Array) {
  267. list = value;
  268. } else {
  269. list = (value || "").split(",");
  270. }
  271. } else {
  272. if (value) {
  273. list = [value];
  274. }
  275. }
  276. // 比较数据,避免重复动画
  277. if (
  278. !this.urls.some((e) => {
  279. return list.includes(e.url);
  280. })
  281. ) {
  282. this.fileList = list.filter(Boolean).map((url) => {
  283. return {
  284. url,
  285. name: path.basename(url),
  286. uid: url
  287. };
  288. });
  289. // 设置 URLS
  290. this.urls = cloneDeep(this.fileList);
  291. }
  292. },
  293. // 更新值
  294. update() {
  295. const urls = this.urls
  296. .filter((e) => Boolean(e.url))
  297. .map((e) => e.url)
  298. .join(",");
  299. this.$emit("input", urls);
  300. this.$emit("change", urls);
  301. },
  302. // 追加文件
  303. append(data) {
  304. if (this.multiple) {
  305. this.urls.push(data);
  306. } else {
  307. this.urls = [data];
  308. }
  309. this.update();
  310. },
  311. // 关闭上传加载中
  312. done() {
  313. this.loading = false;
  314. },
  315. // 删除文件
  316. _onRemove(file) {
  317. this.urls.splice(
  318. this.urls.findIndex((e) => e.uid === file.uid),
  319. 1
  320. );
  321. this.update();
  322. // 删除文件之前的钩子
  323. if (this.onRemove) {
  324. this.onRemove(file, this.urls);
  325. }
  326. },
  327. // 预览图片
  328. _onPreview(file) {
  329. this.preview.visible = true;
  330. this.preview.url = file.url;
  331. if (!file.url) {
  332. let item = this.urls.find((e) => e.uid == file.uid);
  333. if (item) {
  334. this.preview.url = item.url;
  335. }
  336. }
  337. },
  338. // 上传前
  339. _beforeUpload(file) {
  340. this.loading = true;
  341. if (this._limitSize) {
  342. if (file.size / 1024 / 1024 >= this._limitSize) {
  343. this.$message.error(`上传文件大小不能超过 ${this._limitSize}MB!`);
  344. this.done();
  345. return false;
  346. }
  347. }
  348. if (this.beforeUpload) {
  349. return this.beforeUpload(file, {
  350. done: this.done
  351. });
  352. }
  353. return true;
  354. },
  355. // 上传成功
  356. _onSuccess(res, file) {
  357. this.loading = false;
  358. this.append({
  359. url: res.data,
  360. name: file.raw.name,
  361. uid: file.raw.uid
  362. });
  363. // 文件上传成功时的钩子
  364. if (this.onSuccess) {
  365. this.onSuccess(res, file.raw, this.urls);
  366. }
  367. },
  368. // 重设上传请求
  369. httpRequest(req) {
  370. const isRename = isEmpty(this.rename) ? this.conf.rename : this.rename;
  371. const { mode } = this.upload;
  372. // 多种上传请求
  373. const upload = (file) => {
  374. return new Promise((resolve, reject) => {
  375. const next = (res) => {
  376. let data = new FormData();
  377. for (let i in res) {
  378. if (i != "host") {
  379. data.append(i, res[i]);
  380. }
  381. }
  382. let fileName = file.name;
  383. // 是否以 uuid 重新命名
  384. if (isRename) {
  385. fileName = uuidv4() + "." + last((file.name || "").split("."));
  386. }
  387. data.append("key", `app/${fileName}`);
  388. data.append("file", file);
  389. // 上传
  390. this.$service.common
  391. .request({
  392. url: res.host,
  393. method: "POST",
  394. headers: {
  395. "Content-Type": "multipart/form-data"
  396. },
  397. data,
  398. onUploadProgress: (e) => {
  399. if (this.onProgress) {
  400. e.percent = parseInt((e.loaded / e.total) * 100);
  401. this.onProgress(e, req.file);
  402. }
  403. }
  404. })
  405. .then((res) => {
  406. if (mode === "local") {
  407. resolve(res);
  408. } else {
  409. resolve(`${res.host}/app/${fileName}`);
  410. }
  411. })
  412. .catch((err) => {
  413. reject(err);
  414. });
  415. };
  416. if (mode == "local") {
  417. next({
  418. host: "/upload"
  419. });
  420. } else {
  421. this.$service.common
  422. .upload()
  423. .then((res) => {
  424. if (isDev) {
  425. res.host = "@/oss-upload";
  426. }
  427. next(res);
  428. })
  429. .catch(reject);
  430. }
  431. });
  432. };
  433. this.loading = true;
  434. upload(req.file)
  435. .then((url) => {
  436. this._onSuccess({ data: url }, { raw: req.file });
  437. })
  438. .catch((err) => {
  439. console.error("upload error", err);
  440. this.$message.error(err);
  441. // 文件上传失败时的钩子
  442. if (this.onError) {
  443. this.onError(err, req.file);
  444. }
  445. })
  446. .done(() => {
  447. this.loading = false;
  448. });
  449. }
  450. }
  451. };
  452. </script>
  453. <style lang="scss" scoped>
  454. .cl-upload {
  455. display: flex;
  456. flex-wrap: wrap;
  457. &__hidden {
  458. height: 0;
  459. width: 0;
  460. }
  461. &.is-multiple {
  462. .cl-upload__wrap {
  463. margin-right: 10px;
  464. }
  465. }
  466. &--default {
  467. &:not(.is-drag) {
  468. /deep/.el-upload {
  469. display: flex;
  470. align-items: center;
  471. justify-content: center;
  472. border: 1px dashed #d9d9d9;
  473. border-radius: 6px;
  474. cursor: pointer;
  475. position: relative;
  476. overflow: hidden;
  477. height: 100%;
  478. &:hover {
  479. border-color: #409eff;
  480. }
  481. .cl-upload__cover {
  482. img {
  483. display: block;
  484. height: 100%;
  485. width: 100%;
  486. }
  487. }
  488. i {
  489. font-size: 28px;
  490. color: #8c939d;
  491. }
  492. }
  493. }
  494. }
  495. &--picture-card {
  496. /deep/.el-upload {
  497. .cl-upload__icon {
  498. position: relative;
  499. top: 4px;
  500. }
  501. }
  502. }
  503. &__icon + span {
  504. margin-left: 5px;
  505. }
  506. &__text {
  507. font-size: 14px;
  508. }
  509. }
  510. </style>