imageRequest.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // const { request } = require('../utils/util.js')
  2. import strings from '../utils/strings.js';
  3. module.exports = {
  4. // 上传图片到服务器
  5. uploadImage: (filePath, formData = {}) => {
  6. try {
  7. var value = wx.getStorageSync('token') || "";
  8. if (!strings.isEmpty(value)) {
  9. const resData = JSON.parse(value);
  10. Authorization = resData.token;
  11. }
  12. } catch (e) {
  13. Authorization = "";
  14. }
  15. console.log("Authorization:", Authorization)
  16. return new Promise((resolve, reject) => {
  17. // 拼接地址
  18. var baseUrl = getApp().globalData.baseUrl;
  19. let url = '/mini/wx/image/getUrl';
  20. let fullurl = `${baseUrl}${url}`;
  21. console.log("上传图片参数:", fullurl, filePath)
  22. wx.uploadFile({
  23. url: fullurl, // 替换为你的服务器地址
  24. filePath: filePath,
  25. name: 'file', // 文件对应的 key,后端需要根据这个 key 获取文件
  26. formData: formData, // 其他需要上传的表单数据,
  27. header: Object.assign({
  28. "content-type": "multipart/form-data",
  29. "appid": "wx08f94a3e90881910",
  30. "Authorization": Authorization
  31. },),
  32. responseType: 'arraybuffer',
  33. success: (res) => {
  34. console.log("上传图片返回:", res);
  35. try {
  36. // 检查响应头中的 Content-Type
  37. const contentType = res.header['Content-Type'] || res.header['content-type'];
  38. console.log("上传图片返回2:", contentType);
  39. if (contentType && contentType.includes('image/jpeg')) {
  40. // 服务器返回的是图片数据
  41. console.log("上传图片返回3:", res.data);
  42. resolve(dataUrl);
  43. } else {
  44. // 服务器返回的不是图片数据
  45. const data = JSON.parse(res.data ?? "{}");
  46. resolve(data);
  47. }
  48. } catch (e) {
  49. reject(new Error('解析服务器响应失败', e));
  50. }
  51. },
  52. fail: (err) => {
  53. console.log("上传图片返回2:", err);
  54. reject(new Error('上传失败: ' + err.errMsg));
  55. }
  56. });
  57. });
  58. }
  59. }