Ionic Capacitor应用使用XHR上传相机捕获图片失败求助
问题描述
尝试使用Ionic + Capacitor将相机捕获的图片上传至Cloudinary,使用的代码如下:
var url = 'https://api.cloudinary.com/v1_1/' + this.cloudName + '/image/upload'; var xhr = new XMLHttpRequest(); var fd = new FormData(); xhr.open('POST', url, true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.setRequestHeader("Access-Control-Allow-Origin","*") xhr.onreadystatechange = (e) => { this.loading = false; if (xhr.readyState == 4 && xhr.status == 200) { // File uploaded successfully var response = JSON.parse(xhr.responseText); var url = response.secure_url; // Create a thumbnail of the uploaded image, with 150px width var tokens = url.split('/'); tokens.splice(-2, 0, 'w_150,c_scale'); var img = new Image(); // HTML5 Constructor img.src = tokens.join('/'); img.alt = response.public_id; document.body.appendChild(img); //window.alert(url); this.imageUrl = url; this.capturedImage = this.base64Image; //alert('capture:' + capturedImage); }else{ console.log("unable to load image to the cloud" + xhr.readyState + ":" + xhr.status + ":" + xhr.responseText) } }; fd.append('upload_preset', this.unsignedUploadPreset); fd.append('tags', emailid); // Optional - add tag for image admin in Cloudinary fd.append('file', this.base64Image); xhr.send(fd);
上传失败后,控制台输出:unable to load image to the cloud 4:0:,请求协助排查问题。
排查方案
- 移除错误请求头:
Access-Control-Allow-Origin是服务端返回的响应头,客户端无需设置,直接删除xhr.setRequestHeader("Access-Control-Allow-Origin","*")这行代码,该设置会导致请求被浏览器拦截。 - 校验Base64格式:Cloudinary要求Base64图片必须带完整前缀(如
data:image/jpeg;base64,xxxxxx),如果this.base64Image只有编码内容没有前缀,需要补充完整。 - 核对配置参数:确认
this.cloudName和this.unsignedUploadPreset配置正确,且该上传预设的模式已设为「未签名」,同时检查预设是否限制了上传域名(若有配置需确保当前应用域名在允许列表内)。 - 捕获详细错误:状态码0通常对应CORS拦截或连接中断,建议通过浏览器开发者工具的「网络」面板查看请求的详细报错,也可以给XHR添加
onerror事件捕获更多信息:xhr.onerror = () => { console.error('请求错误详情:', xhr.statusText); }; - 检查Capacitor权限:若在iOS/Android端测试,需确认网络权限配置:iOS需在
Info.plist中确保NSAppTransportSecurity允许HTTPS请求;Android需在AndroidManifest.xml中添加<uses-permission android:name="android.permission.INTERNET" />。
内容的提问来源于stack exchange,提问作者Moblize IT
相关产品推荐
相关产品推荐

