|
|
@@ -46,6 +46,56 @@ function parseUploadResponse(raw) {
|
|
|
return ''
|
|
|
}
|
|
|
|
|
|
+/**
|
|
|
+ * 上传前解码并压缩图片,降低 App 端大图 / HEIC 导致的内存闪退。
|
|
|
+ *
|
|
|
+ * @param {string} src
|
|
|
+ * @returns {Promise<string>} 可用于 uploadFile 的本地路径
|
|
|
+ */
|
|
|
+export function prepareImageForUpload(src) {
|
|
|
+ return new Promise((resolve) => {
|
|
|
+ const fallback = () => resolve(src || '')
|
|
|
+ if (!src) {
|
|
|
+ fallback()
|
|
|
+ return
|
|
|
+ }
|
|
|
+ const compress = (path, width = 0, height = 0) => {
|
|
|
+ if (typeof uni.compressImage !== 'function') {
|
|
|
+ resolve(path)
|
|
|
+ return
|
|
|
+ }
|
|
|
+ const opts = {
|
|
|
+ src: path,
|
|
|
+ quality: 60,
|
|
|
+ success: (res) => resolve((res && res.tempFilePath) || path),
|
|
|
+ fail: () => resolve(path)
|
|
|
+ }
|
|
|
+ const w = Number(width) || 0
|
|
|
+ const h = Number(height) || 0
|
|
|
+ if (w > 1280 || h > 1280) {
|
|
|
+ if (w >= h) opts.compressedWidth = 1280
|
|
|
+ else opts.compressedHeight = 1280
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ uni.compressImage(opts)
|
|
|
+ } catch (_) {
|
|
|
+ resolve(path)
|
|
|
+ }
|
|
|
+ }
|
|
|
+ uni.getImageInfo({
|
|
|
+ src,
|
|
|
+ success: (info) => {
|
|
|
+ const path = (info && info.path) || src
|
|
|
+ compress(path, info && info.width, info && info.height)
|
|
|
+ },
|
|
|
+ fail: () => {
|
|
|
+ // 解码失败时仍尝试压缩原路径(部分机型 getImageInfo 对 HEIC 不稳定)
|
|
|
+ compress(src)
|
|
|
+ }
|
|
|
+ })
|
|
|
+ })
|
|
|
+}
|
|
|
+
|
|
|
/**
|
|
|
* 获取图片上传配置(wanlshop/common/uploadData)
|
|
|
*/
|
|
|
@@ -61,24 +111,31 @@ export async function fetchUploadConfig() {
|
|
|
*/
|
|
|
export function uploadImageFile(filePath, config) {
|
|
|
return new Promise((resolve, reject) => {
|
|
|
- const uploadurl = resolveUploadUrl(config.uploadurl)
|
|
|
+ const uploadurl = resolveUploadUrl(config && config.uploadurl)
|
|
|
if (!uploadurl) {
|
|
|
reject(new Error('上传地址无效'))
|
|
|
return
|
|
|
}
|
|
|
- const formData = config.storage === 'local' ? {} : (config.multipart || {})
|
|
|
- uni.uploadFile({
|
|
|
+ if (!filePath) {
|
|
|
+ reject(new Error('图片文件无效'))
|
|
|
+ return
|
|
|
+ }
|
|
|
+ const opts = {
|
|
|
url: uploadurl,
|
|
|
filePath,
|
|
|
name: 'file',
|
|
|
- formData,
|
|
|
success: (res) => {
|
|
|
const url = parseUploadResponse(res.data)
|
|
|
if (url) resolve(url)
|
|
|
else reject(new Error('上传失败'))
|
|
|
},
|
|
|
fail: (err) => reject(err || new Error('上传失败'))
|
|
|
- })
|
|
|
+ }
|
|
|
+ // local 不传 formData;非 local 才带 multipart(与参考工程一致)
|
|
|
+ if (config && config.storage !== 'local' && config.multipart) {
|
|
|
+ opts.formData = config.multipart
|
|
|
+ }
|
|
|
+ uni.uploadFile(opts)
|
|
|
})
|
|
|
}
|
|
|
|