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的值怎么算的没有去深究了,最后还是选择的原生...

相关推荐
少恭写代码1 天前
duxapp 2025-03-29 更新 编译结束的复制逻辑等
react native·小程序·taro
少恭写代码2 天前
在Taro中开发一个跨端Svg组件,同时支持小程序、H5、React Native
react native·小程序·taro
菜鸟una3 天前
【taro3 + vue3 + webpack4】在微信小程序中的请求封装及使用
前端·vue.js·微信小程序·小程序·typescript·taro
PyAIGCMaster8 天前
taro的学习记录
学习·taro
帅次10 天前
Flutter TabBar / TabBarView 详解
android·flutter·ios·小程序·iphone·taro·reactnative
雨中的风铃子14 天前
taro小程序如何实现大文件(视频、图片)后台下载功能?
小程序·音视频·taro
梦魇泪25 天前
实践项目开发-hbmV4V20250407-跨平台开发框架深度解析与VSCode一站式开发实践
vscode·react.js·taro
郑叹20031 个月前
taro中使用captcha
微信小程序·taro
ace_TiAmo1 个月前
React8+taro开发微信小程序,实现lottie动画
微信小程序·小程序·react·taro