hookehuyr

🦄 refactor(上传图片模块): API书写方式async简化

1 /* 1 /*
2 * @Date: 2022-06-17 14:54:29 2 * @Date: 2022-06-17 14:54:29
3 * @LastEditors: hookehuyr hookehuyr@gmail.com 3 * @LastEditors: hookehuyr hookehuyr@gmail.com
4 - * @LastEditTime: 2022-06-17 14:58:17 4 + * @LastEditTime: 2022-06-18 22:18:46
5 * @FilePath: /tswj/src/api/common.js 5 * @FilePath: /tswj/src/api/common.js
6 * @Description: 通用接口 6 * @Description: 通用接口
7 */ 7 */
8 -import { fn, fetch } from '@/api/fn'; 8 +import { fn, fetch, uploadFn } from '@/api/fn';
9 9
10 const Api = { 10 const Api = {
11 SMS: '/srv/?a=sms', 11 SMS: '/srv/?a=sms',
12 + TOKEN: '/srv/?a=upload',
13 + SAVE_FILE: '/srv/?a=upload&t=save_file',
12 } 14 }
13 15
14 /** 16 /**
...@@ -17,3 +19,29 @@ const Api = { ...@@ -17,3 +19,29 @@ const Api = {
17 * @returns 19 * @returns
18 */ 20 */
19 export const smsAPI = (params) => fn(fetch.post(Api.SMS, params)); 21 export const smsAPI = (params) => fn(fetch.post(Api.SMS, params));
22 +
23 +/**
24 + * @description: 获取七牛token
25 + * @param {*} filename 文件名
26 + * @param {*} file 图片base64
27 + * @returns
28 + */
29 +export const qiniuTokenAPI = (params) => fn(fetch.stringifyPost(Api.TOKEN, params));
30 +
31 +/**
32 + * @description: 上传七牛
33 + * @param {*}
34 + * @returns
35 + */
36 +export const qiniuUploadAPI = (url, data, config) => uploadFn(fetch.basePost(url, data, config));
37 +
38 +/**
39 + * @description: 保存图片
40 + * @param {*} format
41 + * @param {*} hash
42 + * @param {*} height
43 + * @param {*} width
44 + * @param {*} filekey
45 + * @returns
46 + */
47 +export const saveFileAPI = (params) => fn(fetch.stringifyPost(Api.SAVE_FILE, params));
......
1 /* 1 /*
2 * @Date: 2022-05-18 22:56:08 2 * @Date: 2022-05-18 22:56:08
3 * @LastEditors: hookehuyr hookehuyr@gmail.com 3 * @LastEditors: hookehuyr hookehuyr@gmail.com
4 - * @LastEditTime: 2022-06-13 15:22:55 4 + * @LastEditTime: 2022-06-18 22:07:50
5 * @FilePath: /tswj/src/api/fn.js 5 * @FilePath: /tswj/src/api/fn.js
6 * @Description: 文件描述 6 * @Description: 文件描述
7 */ 7 */
8 import axios from '@/utils/axios'; 8 import axios from '@/utils/axios';
9 import { Toast } from 'vant'; 9 import { Toast } from 'vant';
10 +import qs from 'Qs'
10 11
11 /** 12 /**
12 * 网络请求功能函数 13 * 网络请求功能函数
...@@ -36,6 +37,30 @@ export const fn = (api) => { ...@@ -36,6 +37,30 @@ export const fn = (api) => {
36 }) 37 })
37 } 38 }
38 39
40 +// 七牛返回格式
41 +export const uploadFn = (api) => {
42 + return api
43 + .then(res => {
44 + if (res.statusText === 'OK') {
45 + return res.data || true;
46 + } else {
47 + // tslint:disable-next-line: no-console
48 + console.warn(res);
49 + if (!res.data.show) return false;
50 + Toast({
51 + icon: 'close',
52 + message: res.data.msg
53 + });
54 + return false;
55 + }
56 + })
57 + .catch(err => {
58 + // tslint:disable-next-line: no-console
59 + console.error(err);
60 + return false;
61 + })
62 +}
63 +
39 /** 64 /**
40 * 统一 GET/POST 不同传参形式 65 * 统一 GET/POST 不同传参形式
41 */ 66 */
...@@ -45,5 +70,11 @@ export const fetch = { ...@@ -45,5 +70,11 @@ export const fetch = {
45 }, 70 },
46 post: function (api, params) { 71 post: function (api, params) {
47 return axios.post(api, params) 72 return axios.post(api, params)
73 + },
74 + stringifyPost: function (api, params) {
75 + return axios.post(api, qs.stringify(params))
76 + },
77 + basePost: function (url, data, config) {
78 + return axios.post(url, data, config)
48 } 79 }
49 } 80 }
......
1 +/*
2 + * @Date: 2022-05-10 12:15:14
3 + * @LastEditors: hookehuyr hookehuyr@gmail.com
4 + * @LastEditTime: 2022-06-18 22:30:10
5 + * @FilePath: /tswj/src/composables/useUpload.js
6 + * @Description: 图片上传模块
7 + */
1 import { v4 as uuidv4 } from 'uuid'; 8 import { v4 as uuidv4 } from 'uuid';
2 import { ref, reactive } from 'vue' 9 import { ref, reactive } from 'vue'
3 -import axios from '@/utils/axios'; 10 +import { qiniuTokenAPI, qiniuUploadAPI, saveFileAPI } from '@/api/common'
4 -import { Toast } from 'vant';
5 -import qs from 'Qs'
6 11
7 -// tslint:disable
8 export const useUpload = () => { 12 export const useUpload = () => {
9 let lock_btn = ref(false); // 保存按钮锁 13 let lock_btn = ref(false); // 保存按钮锁
10 let fileList = ref([]); 14 let fileList = ref([]);
11 - let metaId = ref('');
12 let upload_image = reactive({ src: '' }); 15 let upload_image = reactive({ src: '' });
13 - const afterRead = (res) => { 16 + const afterRead = async (res) => {
14 lock_btn.value = true; // 上传开始, 不能保存 17 lock_btn.value = true; // 上传开始, 不能保存
15 let affix = uuidv4(); 18 let affix = uuidv4();
16 // 此时可以自行将文件上传至服务器 19 // 此时可以自行将文件上传至服务器
17 let dataURL = res.content; 20 let dataURL = res.content;
18 let base64url = dataURL.slice(dataURL.indexOf(',') + 1); // 截取前缀的base64 data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAnoAAAJeCAYAA....... 21 let base64url = dataURL.slice(dataURL.indexOf(',') + 1); // 截取前缀的base64 data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAnoAAAJeCAYAA.......
19 // 获取七牛token 22 // 获取七牛token
20 - axios.post('/srv/?a=upload', qs.stringify({ 23 + const { token, key, code } = await qiniuTokenAPI({ filename: `${affix}_${res.file.name}`, file: base64url });
21 - filename: `${affix}_${res.file.name}`, 24 + if (code === 1) {
22 - file: base64url
23 - }))
24 - .then(res => {
25 - if (res.data.code === 1) {
26 let config = { 25 let config = {
27 headers: { 26 headers: {
28 'Content-Type': 'application/octet-stream', 27 'Content-Type': 'application/octet-stream',
29 - 'Authorization': 'UpToken ' + res.data.token, // UpToken后必须有一个 ' '(空格) 28 + 'Authorization': 'UpToken ' + token, // UpToken后必须有一个 ' '(空格)
30 } 29 }
31 } 30 }
32 // 上传七牛服务器 31 // 上传七牛服务器
33 - axios.post('http://upload.qiniup.com/putb64/-1/key/' + res.data.key, base64url, config) 32 + const { filekey, hash, image_info } = await qiniuUploadAPI('http://upload.qiniup.com/putb64/-1/key/' + key, base64url, config)
34 - .then(res => { 33 + if (filekey) {
35 - if (res.data.filekey) { 34 + // 保存图片
36 - let info = res.data; 35 + const { data } = await saveFileAPI({ filekey, hash, format: image_info.format, height: image_info.height, width: image_info.width });
37 - // 保存图片返回ID 36 + upload_image.src = data.src;
38 - axios.post('/srv/?a=upload&t=save_file', qs.stringify({
39 - format: info.image_info.format,
40 - hash: info.hash,
41 - height: info.image_info.height,
42 - width: info.image_info.width,
43 - filekey: info.filekey,
44 - }))
45 - .then(res => {
46 - upload_image.src = res.data.data.src;
47 lock_btn.value = false; // 头像上传完成, 打开锁 37 lock_btn.value = false; // 头像上传完成, 打开锁
48 - })
49 - .catch(err => {
50 - console.error(err);
51 - })
52 - } else {
53 - console.warn(res);
54 - if (!res.data.show) return false;
55 - Toast({
56 - icon: 'close',
57 - message: res.data.msg
58 - });
59 } 38 }
60 - })
61 - .catch(err => {
62 - console.error(err);
63 - })
64 - } else {
65 - console.warn(res);
66 } 39 }
67 - })
68 - .catch(err => {
69 - console.error(err);
70 - })
71 }; 40 };
72 const beforeDelete = () => { // 删除图片回调 41 const beforeDelete = () => { // 删除图片回调
73 upload_image.src = ''; 42 upload_image.src = '';
...@@ -78,7 +47,6 @@ export const useUpload = () => { ...@@ -78,7 +47,6 @@ export const useUpload = () => {
78 lock_btn, 47 lock_btn,
79 fileList, 48 fileList,
80 upload_image, 49 upload_image,
81 - metaId,
82 afterRead, 50 afterRead,
83 beforeDelete 51 beforeDelete
84 } 52 }
......
...@@ -38,14 +38,14 @@ ...@@ -38,14 +38,14 @@
38 <script setup> 38 <script setup>
39 import { useUpload } from '@/composables/useUpload.js' 39 import { useUpload } from '@/composables/useUpload.js'
40 40
41 -import { ref, reactive, onMounted } from 'vue' 41 +import { ref, reactive } from 'vue'
42 import { useRoute, useRouter } from 'vue-router' 42 import { useRoute, useRouter } from 'vue-router'
43 import axios from '@/utils/axios'; 43 import axios from '@/utils/axios';
44 import { Toast } from 'vant'; 44 import { Toast } from 'vant';
45 import _ from 'lodash' 45 import _ from 'lodash'
46 import { styleColor } from '@/constant.js'; 46 import { styleColor } from '@/constant.js';
47 47
48 -const { lock_btn, fileList, upload_image, metaId, afterRead, beforeDelete } = useUpload(); // 上传图片模块 48 +const { lock_btn, fileList, upload_image, afterRead, beforeDelete } = useUpload(); // 上传图片模块
49 49
50 const $route = useRoute(); 50 const $route = useRoute();
51 const $router = useRouter(); 51 const $router = useRouter();
......