使用fetch/PUT上传图片至BunnyCDN失败问题排查
使用Fetch通过PUT请求上传图片到BunnyCDN失败的调整方案
我尝试用Fetch发送PUT请求把图片上传到BunnyCDN,但直接把图片放入请求体的方式无法成功上传,请问有哪些可以调整的地方?
const uploadpicture = async () => { console.log("uploadpic") //here use then props.route.params.image etc let randomid = uuid() let bodyy = new FormData() bodyy.append("image",props.route.params.image.uri) const options = { method: 'PUT', headers: { 'content-type': 'application/octet-stream', AccessKey: '185e0bd5-1e29-492e-811d6cde3520-4ebe-4c15' }, body: bodyy }; fetch(`https://storage.bunnycdn.com/premvanaprogr/${currentUserObject.uid}/${randomid}.jpg`, options) .then(response => response.json()) .then(response => console.log(response)) .catch(err => console.error(err)) }
调整方案:
- 请求体与Content-Type不匹配:你用了
FormData作为PUT请求的body,但设置了content-type: application/octet-stream,两者冲突。BunnyCDN的PUT上传要求直接传文件二进制数据,而非FormData,需要把图片的Blob/ArrayBuffer作为请求体。 - 图片URI未转二进制:
props.route.params.image.uri只是路径字符串,不是二进制数据。必须先把这个URI转换成Blob或ArrayBuffer才能作为请求体上传。 - Content-Type设置不准确:应该根据图片实际类型设置,比如
image/jpeg,而非通用的application/octet-stream,这样BunnyCDN能更准确识别文件类型。 - 错误处理不完整:Fetch只有在网络错误时才会进入catch,HTTP状态码错误(4xx/5xx)不会触发,需要手动检查
response.ok判断上传是否成功。另外BunnyCDN PUT成功后返回空响应,调用response.json()会报错。
修正后的示例代码:
const uploadpicture = async () => { console.log("uploadpic"); let randomid = uuid(); const imageUri = props.route.params.image.uri; try { // 将图片URI转换为Blob const imgResponse = await fetch(imageUri); const imageBlob = await imgResponse.blob(); const options = { method: 'PUT', headers: { 'Content-Type': imageBlob.type, 'AccessKey': '185e0bd5-1e29-492e-811d6cde3520-4ebe-4c15' }, body: imageBlob }; const uploadResponse = await fetch(`https://storage.bunnycdn.com/premvanaprogr/${currentUserObject.uid}/${randomid}.jpg`, options); if (!uploadResponse.ok) { throw new Error(`上传失败,状态码:${uploadResponse.status}`); } console.log("上传成功"); } catch (err) { console.error(err); } };
额外注意:
- 绝对不要把
AccessKey写在前端代码里,这会导致密钥泄露,被他人盗用存储资源。正确做法是通过后端代理上传,前端把图片传给自己的后端,再由后端调用BunnyCDN的API。 - 如果是React Native环境,处理图片URI转Blob可能需要额外调整,比如使用
react-native-fs库读取文件二进制数据。
内容的提问来源于stack exchange,提问作者vana22
相关产品推荐
相关产品推荐

