taro h5 formData上传图片的坑-Required request part ‘file‘ is not present

描述:用formData上传图片

1、生成formData

javascript 复制代码
const formData = new FormData()
formData.append('file', data) // data是file
formData.append('xxx', 'xxx') // 添加其他参数

2、用taro.request请求

javascript 复制代码
Taro.request({
	url: 'xxxx',
	data: formData,
	header: {
		'Content-Type': 'multipart/form-data;'
	},
	method: 'POST',
})

结果:报错500

3、用原生请求

javascript 复制代码
let xmlhttp = new XMLHttpRequest()
xmlhttp.open('post', 'xxxx')
xmlhttp.setRequestHeader('token', 'xxx')
xmlhttp.onreadystatechange = function (res) {
  if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
    console.log(xmlhttp.response)
  }
}
xmlhttp.send(formData)

结果:成功


注意,并没有设置content-type, 但是请求自动添加了content-type

4、对比后发现

原生的比taro多了boundary, boundary是分割线, 那把这个boundary复制下行不行呢?
!!!是不行的

5、总结

网上很多资料显示,formData上传时不需要设置content-type, 而taro.request默认是设置的content-type=application/json, 就算手动设置了,也不会自动加boundary, 而这个boundary的值怎么算的没有去深究了,最后还是选择的原生...

相关推荐
Thetimezipsby5 天前
基于Taro4打造的一款最新版微信小程序、H5的多端开发简单模板
前端·javascript·微信小程序·typescript·html5·taro
gitboyzcf8 天前
基于Taro4最新版微信小程序、H5的多端开发简单模板
前端·vue.js·taro
浩星10 天前
react+taro中使用vant 工具:taroify
前端·react.js·taro
浩星10 天前
react+taro的使用整理
前端·react.js·taro
浩星19 天前
react+taro打包到不同小程序
react.js·小程序·taro
namehu19 天前
🚀 2025 年最新教程:在 React Native 0.70+ 项目中接入 react-native-wechat-lib
react native·微信·taro
摸着石头过河的石头1 个月前
taro3.x-4.x路由拦截如何破?
前端·taro
少恭写代码1 个月前
duxapop 更新 2025-05-16 新增Svg编辑器 修复Svg多个Bug
小程序·taro
超级土豆粉1 个月前
Taro Hooks 完整分类详解
前端·javascript·react.js·taro