index.vue
7.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
<!--
* @Date: 2022-08-31 16:16:49
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2022-11-21 14:54:30
* @FilePath: /data-table/src/components/ImageUploaderField/index.vue
* @Description: 图片上传控件
-->
<template>
<div class="image-uploader-field">
<div class="label">
{{ item.component_props.label
}}<span v-if="item.component_props.required"> *</span>
</div>
<div style="padding: 1rem">
<van-uploader
upload-icon="add"
:before-read="beforeRead"
:after-read="afterRead"
:before-delete="beforeDelete"
v-model="fileList"
:multiple="item.component_props.multiple"
/>
</div>
<div class="type-text">上传格式:{{ type_text }}</div>
<div
v-if="show_empty"
class="van-field__error-message"
style="padding: 0 1rem 1rem 1rem"
>
图片上传不能为空
</div>
</div>
<van-overlay :show="loading">
<div class="wrapper" @click.stop>
<van-loading vertical color="#FFFFFF">上传中...</van-loading>
</div>
</van-overlay>
</template>
<script setup>
/**
* 图片上传
* @param name[String] 组件名称
* @param image_type[Array] 图片上传类型
* @param multiple[Boolean] 图片多选
*/
import { showSuccessToast, showFailToast } from "vant";
import _ from "lodash";
import { v4 as uuidv4 } from "uuid";
import { qiniuTokenAPI, qiniuUploadAPI, saveFileAPI } from "@/api/common";
import BMF from "browser-md5-file";
import { useRoute } from "vue-router";
import axios from "axios";
import { getEtag } from "@/utils/qetag.js"; // 生成hash值
const $route = useRoute();
const props = defineProps({
item: Object,
});
const emit = defineEmits(["active"]);
const show_empty = ref(false);
// 文件类型中文页面显示
const type_text = computed(() => {
return props.item.component_props.image_type;
});
// 上传前置处理
const beforeRead = (file) => {
// 类型限制
const image_types = _.map(
props.item.component_props.image_type.split("/"),
(item) => `image/${item}`
);
let flag = true;
if (_.isArray(file)) {
// 多张图片
const types = _.difference(_.uniq(_.map(file, (item) => item.type)), image_types); // 数组返回不能上传的类型
if (types.length) {
flag = false;
showFailToast("请上传指定格式图片");
}
} else {
if (!_.includes(image_types, file.type)) {
showFailToast("请上传指定格式图片");
flag = false;
}
}
return flag;
};
/********** 上传七牛云获取图片地址 ***********/
const loading = ref(false);
const formCode = $route.query.code; // 表单code
const uuid = () => {
let s = [];
let hexDigits = "0123456789abcdef";
for (var i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4";
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
s[8] = s[13] = s[18] = s[23] = "-";
var uuid = s.join("");
return uuid;
};
const uploadQiniu = async (file, token, filename, md5) => {
let formData = new FormData();
formData.append("file", file); // 通过append向form对象添加数据
formData.append("token", token);
formData.append("key", filename);
let config = {
headers: { "Content-Type": "multipart/form-data" },
};
// 自拍图片上传七牛服务器
const { filekey, hash, image_info } = await qiniuUploadAPI(
"http://upload.qiniu.com/",
formData,
config
);
if (filekey) {
// 保存图片
const { data } = await saveFileAPI({
filename,
filekey,
hash: md5,
format: image_info.format,
height: image_info.height,
width: image_info.width,
});
return data;
}
};
/****************** END *******************/
const handleUpload = async (files) => {
// 上传图片流程
loading.value = true;
// 获取HASH值
// const hash = getEtag(files.content);
return new Promise((resolve, reject) => {
// 获取MD5值
const bmf = new BMF();
bmf.md5(
files.file,
async (err, md5) => {
if (err) {
console.log(err);
reject(err);
}
// 获取七牛token
const filename =
"uploadForm/" + formCode + "/" + uuid() + "." + files.file.name.split(".")[1];
const getToken = await qiniuTokenAPI({
name: filename,
hash: md5,
});
// 文件上传七牛云
let imgUrl = "";
// 第一次上传
if (getToken.token) {
files.status = "uploading";
files.message = "上传中...";
imgUrl = await uploadQiniu(files.file, getToken.token, filename, md5);
}
// 重复上传
if (getToken.data) {
imgUrl = getToken.data;
}
resolve(imgUrl);
},
(process) => {
//计算进度
}
);
});
};
// 多选图片上传遍历
var muliUpload = async (files) => {
for (let item of files) {
const res = await handleUpload(item);
// 上传失败提示
if (!res.src) {
item.status = "failed";
item.message = "上传失败";
loading.value = false;
} else {
item.status = "";
item.message = "";
fileList.value.push({
url: res.src,
isImage: true,
});
loading.value = false;
}
}
};
const afterRead = async (files) => {
if (Array.isArray(files)) {
// 多张图片上传files是一个数组
muliUpload(files);
} else {
const imgUrl = await handleUpload(files);
// 上传失败提示
if (!imgUrl.src) {
files.status = "failed";
files.message = "上传失败";
loading.value = false;
} else {
files.status = "";
files.message = "";
fileList.value.push({
meta_id: imgUrl.meta_id,
url: imgUrl.src,
isImage: true,
});
loading.value = false;
}
}
// 过滤非包含URL的图片
fileList.value = fileList.value.filter((item) => {
if (item.url) return item;
});
props.item.value = {
key: "image_uploader",
filed_name: props.item.key,
// value: fileList.value.map((item) => item.url),
value: fileList.value,
};
show_empty.value = false;
emit("active", props.item.value);
console.warn(fileList.value);
};
const beforeDelete = (files) => {
fileList.value = fileList.value.filter((item) => {
if (item.url !== files.url) return item;
});
props.item.value = {
key: "image_uploader",
filed_name: props.item.key,
// value: fileList.value.map((item) => item.url),
value: fileList.value,
};
emit("active", props.item.value);
};
const fileList = ref([
// { url: "https://fastly.jsdelivr.net/npm/@vant/assets/leaf.jpeg" },
// Uploader 根据文件后缀来判断是否为图片文件
// 如果图片 URL 中不包含类型信息,可以添加 isImage 标记来声明
// { url: 'https://cloud-image', isImage: true },
]);
const validImageUploader = () => {
// 必填项 未上传图片
if (props.item.component_props.required && !fileList.value.length) {
show_empty.value = true;
} else {
show_empty.value = false;
}
return !show_empty.value;
};
defineExpose({ validImageUploader });
</script>
<style lang="less" scoped>
.image-uploader-field {
.label {
padding: 1rem 1rem 0 1rem;
font-size: 0.9rem;
font-weight: bold;
span {
color: red;
}
}
.type-text {
font-size: 0.9rem;
margin-left: 1rem;
padding-bottom: 1rem;
color: gray;
}
}
.wrapper {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
}
.block {
width: 120px;
height: 120px;
background-color: #fff;
}
</style>