简体   繁体   中英

ionic capacitor app Failing to upload file using xhr

i am trying to upload image captured from camera using ionic and capacitor and below code i am using:

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);

it prints: unable to load image to the cloud 4:0:

I'm a little confused by your code because it looks like you are trying to access the response before you've actually sent anything. I would recommend using one of the Cloudinary SDKs as it will make your life a lot easier.

https://cloudinary.com/documentation/image_upload_api_reference#upload_examples

Here is an example of another upload using Ionic and Capacitor.

https://devdactic.com/ionic-image-upload-capacitor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM