问题描述
- 官方提供的文件上传API是wx.uploadFile,一次只能上传一个文件,网上的解决方案大多都是循环遍历发送,感觉有点扯犊子。
使用
const Multipart = require('../../utils/Multipart.min.js')
- 2、在方法中上传文件(注意 fields 和 files 格式)
const fields = [
{ // 表单的其他字段
name: 'user_id',
value: 1
},
// .....
]
const files = [
{ // 要上传的文件 数组
name: 'file',
filePath: img
},
// .....
]
let res = new Multipart({
fields, // 表单数据
files // 上传文件数据
}).submit(app.globalData.requestUrl + "/myurl")
.then((res)=>{
console.log(res.data)
// .....
}).catch((e)=>{
wx.showToast({
icon:'none',
title: '提交失败,请重试'
})
})
// 新增报修接口封装
const v = '/japi'
const addAfterSaleRepair = (params) => {
let {
fileList,
...formData
} = params
// 有图片上传操作(参照 Multipart.min.js)
if (fileList && fileList instanceof Array && fileList.length > 0) {
let data = getDataAndSign(v, '/api/repairApply', formData, 2)
// 非文件参数(数组)
let fields = Object.keys(data).map(key => ({
name: key,
value: data[key],
}))
// 文件参数(数组)
let files = []
fileList.forEach(item => {
files.push({
name: item.name,
filePath: item.filePath
})
})
return requestMultipart('/api/repairApply', fields, files, v, 2)
}
// 无图片上传操作
if (!fileList || (fileList instanceof Array && fileList.length <= 0)) {
let data = getDataAndSign(v, '/api/repairApply', formData, 2)
return request('/api/repairApply', 'POST', data, v, 2)
}
}
// form表单数据处理
let { planeSn, username, phone, description } = formData // 表单数据
let handleData = {plane_sn: planeSn, username, phone, describe: description}
let files = []
this.data.fileList.forEach(item => {
files.push({name: 'image', filePath: item.url})
})
handleData.fileList = files // 接口 fileList 字段
wx.showLoading({title: '数据上传中'});
addAfterSaleRepair(handleData).then(res => {
if (res.status == 1) {
let id = res.data.id
setTimeout(() => {
wx.navigateTo({
url: '/pages/afterSaleRepair/detail/index?id=' + id
})
}, 1000)
}
})