baseComponent.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. import fetch from 'node-fetch';
  2. import Ids from '../models/ids'
  3. import formidable from 'formidable'
  4. import path from 'path'
  5. import fs from 'fs'
  6. import qiniu from 'qiniu'
  7. import gm from 'gm'
  8. qiniu.conf.ACCESS_KEY = 'Ep714TDrVhrhZzV2VJJxDYgGHBAX-KmU1xV1SQdS';
  9. qiniu.conf.SECRET_KEY = 'XNIW2dNffPBdaAhvm9dadBlJ-H6yyCTIJLxNM_N6';
  10. export default class BaseComponent {
  11. constructor(){
  12. this.idList = ['restaurant_id', 'food_id', 'order_id', 'user_id', 'address_id', 'cart_id', 'img_id', 'category_id', 'item_id', 'sku_id', 'admin_id', 'statis_id'];
  13. this.imgTypeList = ['shop', 'food', 'avatar','default'];
  14. this.uploadImg = this.uploadImg.bind(this)
  15. this.qiniu = this.qiniu.bind(this)
  16. }
  17. async fetch(url = '', data = {}, type = 'GET', resType = 'JSON'){
  18. type = type.toUpperCase();
  19. resType = resType.toUpperCase();
  20. if (type == 'GET') {
  21. let dataStr = ''; //数据拼接字符串
  22. Object.keys(data).forEach(key => {
  23. dataStr += key + '=' + data[key] + '&';
  24. })
  25. if (dataStr !== '') {
  26. dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
  27. url = url + '?' + dataStr;
  28. }
  29. }
  30. let requestConfig = {
  31. method: type,
  32. headers: {
  33. 'Accept': 'application/json',
  34. 'Content-Type': 'application/json'
  35. },
  36. }
  37. if (type == 'POST') {
  38. Object.defineProperty(requestConfig, 'body', {
  39. value: JSON.stringify(data)
  40. })
  41. }
  42. let responseJson;
  43. try {
  44. const response = await fetch(url, requestConfig);
  45. if (resType === 'TEXT') {
  46. responseJson = await response.text();
  47. }else{
  48. responseJson = await response.json();
  49. }
  50. } catch (err) {
  51. console.log('获取http数据失败', err);
  52. throw new Error(err)
  53. }
  54. return responseJson
  55. }
  56. //获取id列表
  57. async getId(type){
  58. if (!this.idList.includes(type)) {
  59. console.log('id类型错误');
  60. throw new Error('id类型错误');
  61. return
  62. }
  63. try{
  64. const idData = await Ids.findOne();
  65. idData[type] ++ ;
  66. await idData.save();
  67. return idData[type]
  68. }catch(err){
  69. console.log('获取ID数据失败');
  70. throw new Error(err)
  71. }
  72. }
  73. async uploadImg(req, res, next){
  74. const type = req.params.type;
  75. try{
  76. //const image_path = await this.qiniu(req, type);
  77. const image_path = await this.getPath(req, res);
  78. res.send({
  79. status: 1,
  80. image_path,
  81. })
  82. }catch(err){
  83. console.log('上传图片失败', err);
  84. res.send({
  85. status: 0,
  86. type: 'ERROR_UPLOAD_IMG',
  87. message: '上传图片失败'
  88. })
  89. }
  90. }
  91. async getPath(req, res){
  92. return new Promise((resolve, reject) => {
  93. const form = formidable.IncomingForm();
  94. form.uploadDir = './public/img';
  95. form.parse(req, async (err, fields, files) => {
  96. let img_id;
  97. try{
  98. img_id = await this.getId('img_id');
  99. }catch(err){
  100. console.log('获取图片id失败');
  101. fs.unlinkSync(files.file.path);
  102. reject('获取图片id失败');
  103. }
  104. const hashName = (new Date().getTime() + Math.ceil(Math.random()*10000)).toString(16) + img_id;
  105. const extname = path.extname(files.file.name);
  106. if (!['.jpg', '.jpeg', '.png'].includes(extname)) {
  107. fs.unlinkSync(files.file.path);
  108. res.send({
  109. status: 0,
  110. type: 'ERROR_EXTNAME',
  111. message: '文件格式错误'
  112. })
  113. reject('上传失败');
  114. return
  115. }
  116. const fullName = hashName + extname;
  117. const repath = './public/img/' + fullName;
  118. try{
  119. fs.renameSync(files.file.path, repath);
  120. gm(repath)
  121. .resize(200, 200, "!")
  122. .write(repath, async (err) => {
  123. // if(err){
  124. // console.log('裁切图片失败');
  125. // reject('裁切图片失败');
  126. // return
  127. // }
  128. resolve(fullName)
  129. })
  130. }catch(err){
  131. console.log('保存图片失败', err);
  132. if (fs.existsSync(repath)) {
  133. fs.unlinkSync(repath);
  134. } else {
  135. fs.unlinkSync(files.file.path);
  136. }
  137. reject('保存图片失败')
  138. }
  139. });
  140. })
  141. }
  142. async qiniu(req, type = 'default'){
  143. return new Promise((resolve, reject) => {
  144. const form = formidable.IncomingForm();
  145. form.uploadDir = './public/img';
  146. form.parse(req, async (err, fields, files) => {
  147. let img_id;
  148. try{
  149. img_id = await this.getId('img_id');
  150. }catch(err){
  151. console.log('获取图片id失败');
  152. fs.unlinkSync(files.file.path);
  153. reject('获取图片id失败')
  154. }
  155. const hashName = (new Date().getTime() + Math.ceil(Math.random()*10000)).toString(16) + img_id;
  156. const extname = path.extname(files.file.name);
  157. const repath = './public/img/' + hashName + extname;
  158. try{
  159. const key = hashName + extname;
  160. await fs.rename(files.file.path, repath);
  161. const token = this.uptoken('node-elm', key);
  162. const qiniuImg = await this.uploadFile(token.toString(), key, repath);
  163. fs.unlinkSync(repath);
  164. resolve(qiniuImg)
  165. }catch(err){
  166. console.log('保存至七牛失败', err);
  167. fs.unlinkSync(files.file.path)
  168. reject('保存至七牛失败')
  169. }
  170. });
  171. })
  172. }
  173. uptoken(bucket, key){
  174. var putPolicy = new qiniu.rs.PutPolicy(bucket+":"+key);
  175. return putPolicy.token();
  176. }
  177. uploadFile(uptoken, key, localFile){
  178. return new Promise((resolve, reject) => {
  179. var extra = new qiniu.io.PutExtra();
  180. qiniu.io.putFile(uptoken, key, localFile, extra, function(err, ret) {
  181. if(!err) {
  182. resolve(ret.key)
  183. } else {
  184. console.log('图片上传至七牛失败', err);
  185. reject(err)
  186. }
  187. });
  188. })
  189. }
  190. }