index.vue 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. <template>
  2. <div class="upload-file">
  3. <el-upload
  4. :action="fileSaveUrl"
  5. :before-upload="handleBeforeUpload"
  6. :file-list="fileList"
  7. :limit="limit"
  8. :on-error="handleUploadError"
  9. :on-exceed="handleExceed"
  10. :show-file-list="false"
  11. :headers="headers"
  12. :data="reqData"
  13. :http-request="uploadFile"
  14. class="upload-file-uploader"
  15. ref="upload">
  16. <!-- 上传按钮 -->
  17. <el-button size="mini" type="primary">选取文件</el-button>
  18. <!-- 上传提示 -->
  19. <div class="el-upload__tip" slot="tip" v-if="showTip">
  20. 请上传
  21. <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
  22. <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
  23. 的文件
  24. </div>
  25. </el-upload>
  26. <!-- 文件列表 -->
  27. <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
  28. <li :key="file.uid" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
  29. <el-link :href="``" :underline="false" target="_blank">
  30. <span class="el-icon-document"> {{ getFileName(file.fileName) }} </span>
  31. </el-link>
  32. <div class="ele-upload-list__item-content-action">
  33. <el-link :underline="false" @click="handleDelete(index)" type="danger">删除</el-link>
  34. </div>
  35. </li>
  36. </transition-group>
  37. </div>
  38. </template>
  39. <script>
  40. import { getToken, getSign } from "@/utils/auth";
  41. import {uploadFileRequest} from "../../api/common";
  42. import { randomStr20 } from '@/utils/util'
  43. export default {
  44. name: "FileUpload",
  45. props: {
  46. // 值
  47. value: [String, Object, Array],
  48. // 数量限制
  49. limit: {
  50. type: Number,
  51. default: 5,
  52. },
  53. // 大小限制(MB)
  54. fileSize: {
  55. type: Number,
  56. default: 5,
  57. },
  58. // 文件类型, 例如['png', 'jpg', 'jpeg']
  59. fileType: {
  60. type: Array,
  61. default: () => ["doc", "xls", "ppt", "txt", "pdf"],
  62. },
  63. // 是否显示提示
  64. isShowTip: {
  65. type: Boolean,
  66. default: true
  67. },
  68. bizType: {
  69. type: String,
  70. default: "template"
  71. }
  72. },
  73. data() {
  74. return {
  75. baseUrl: process.env.VUE_APP_BASE_API,
  76. uploadFileUrl: process.env.VUE_APP_BASE_API + "/api/v1/mp/file/remote/upload/" + this.bizType, // 上传的文件服务器地址
  77. fileSaveUrl: '',
  78. headers: {
  79. Authorization: "Bearer " + getToken(),
  80. },
  81. fileList: [],
  82. reqData: {}
  83. };
  84. },
  85. watch: {
  86. value: {
  87. handler(val) {
  88. if (val) {
  89. let temp = 1;
  90. // 首先将值转为数组
  91. const list = Array.isArray(val) ? val : this.value.split(',');
  92. // 然后将数组转为对象数组
  93. this.fileList = list.map(item => {
  94. if (typeof item === "string") {
  95. item = { name: item, url: item };
  96. }
  97. item.uid = item.uid || new Date().getTime() + temp++;
  98. return item;
  99. });
  100. } else {
  101. this.fileList = [];
  102. return [];
  103. }
  104. },
  105. deep: true,
  106. immediate: true
  107. }
  108. },
  109. computed: {
  110. // 是否显示提示
  111. showTip() {
  112. return this.isShowTip && (this.fileType || this.fileSize);
  113. },
  114. },
  115. methods: {
  116. // 上传前校检格式和大小
  117. handleBeforeUpload(file) {
  118. // 校检文件类型
  119. if (this.fileType) {
  120. let fileExtension = "";
  121. if (file.name.lastIndexOf(".") > -1) {
  122. fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
  123. }
  124. const isTypeOk = this.fileType.some((type) => {
  125. // if (file.type.indexOf(type) > -1) return true;
  126. if (fileExtension && fileExtension.indexOf(type) > -1) return true;
  127. return false;
  128. });
  129. if (!isTypeOk) {
  130. this.$message.error(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
  131. return false;
  132. }
  133. }
  134. // 校检文件大小
  135. if (this.fileSize) {
  136. const isLt = file.size / 1024 / 1024 < this.fileSize;
  137. if (!isLt) {
  138. this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
  139. return false;
  140. }
  141. }
  142. this.getHttpHeader();
  143. return true;
  144. },
  145. // 文件个数超出
  146. handleExceed() {
  147. this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`);
  148. },
  149. // 上传失败
  150. handleUploadError(err) {
  151. this.$message.error("上传失败, 请重试" + err);
  152. },
  153. // 上传成功回调
  154. handleUploadSuccess(res, file, fileList) {
  155. this.$message.success("上传成功");
  156. this.fileList.push({
  157. fileName: res.data.fileName,
  158. fileType: res.data.fileType
  159. });
  160. this.$emit("input", this.listToString(this.fileList));
  161. },
  162. // 删除文件
  163. handleDelete(index) {
  164. this.fileList.splice(index, 1);
  165. this.$emit("input", this.listToString(this.fileList));
  166. },
  167. // 获取文件名称
  168. getFileName(name) {
  169. if (name.lastIndexOf("/") > -1) {
  170. return name.slice(name.lastIndexOf("/") + 1).toLowerCase();
  171. } else {
  172. return "";
  173. }
  174. },
  175. // 对象转成指定字符串分隔
  176. listToString(list, separator) {
  177. let strs = "";
  178. separator = separator || ",";
  179. for (let i in list) {
  180. strs += list[i].url + separator;
  181. }
  182. return strs != '' ? strs.substr(0, strs.length - 1) : '';
  183. },
  184. // 请求头
  185. getHttpHeader() {
  186. let timestamp = parseInt(new Date().getTime()),
  187. nonce = randomStr20();
  188. var sign = getSign(this.reqData || {}, timestamp)
  189. let url = this.uploadFileUrl + '?sign=' + sign + '&nonce=' + nonce;
  190. this.fileSaveUrl = url
  191. var headers = {
  192. "Authorization": "Bearer " + getToken(),
  193. "x-zz-timestamp": timestamp
  194. }
  195. this.headers = headers
  196. },
  197. // 自定义文件上传的实现
  198. uploadFile(param) {
  199. var data = this.reqData || {}
  200. var params = {
  201. file: param.file,
  202. ...data
  203. }
  204. uploadFileRequest(params, this.bizType, this.headers).then(response => {
  205. /*var res = {
  206. fileName: response.data.fileName,
  207. fileType: response.data.fileType
  208. }*/
  209. this.fileList.push({
  210. fileName: response.data.fileName,
  211. fileType: response.data.fileType
  212. });
  213. this.$emit("input", this.fileList);
  214. //this.$emit("input", this.listToString(this.fileList));
  215. //this.loading.close();
  216. // 但是我们上传成功了图片, fileList 里面的值却没有改变,还好有on-change指令可以使用
  217. }).catch(response => {
  218. param.onError()
  219. })
  220. },
  221. }
  222. };
  223. </script>
  224. <style scoped lang="scss">
  225. .upload-file-uploader {
  226. margin-bottom: 5px;
  227. }
  228. .upload-file-list .el-upload-list__item {
  229. border: 1px solid #e4e7ed;
  230. line-height: 2;
  231. margin-bottom: 10px;
  232. position: relative;
  233. }
  234. .upload-file-list .ele-upload-list__item-content {
  235. display: flex;
  236. justify-content: space-between;
  237. align-items: center;
  238. color: inherit;
  239. }
  240. .ele-upload-list__item-content-action .el-link {
  241. margin-right: 10px;
  242. }
  243. </style>