2017-03-29 5 views
0

Ich benutze Javascript, um ein Bild im unsignierten Modus hochladen. Das resultierende Bild ist ein leeres Bild oder ich kann sagen, ein Bild mit schwarzer Farbe gefüllt. nicht sicher, was falsch ist. der Code sieht aus wie folgt:cloudinary Javascript Bild lädt eine leere Datei

var xhttp = new XMLHttpRequest(); 
xhttp.open("POST", "https://api.cloudinary.com/v1_1/mycloud/image/upload", false); 
xhttp.setRequestHeader("Content-type", "application/json"); 

xhttp.onreadystatechange = function() { //Call a function when the state changes. 
    if (xhttp.readyState == 4 && xhttp.status == 200) { 
    alert(xhttp.responseText); 
    } else { 
    alert("Error dude: " + xhttp.statusText); 
    } 
} 

var parameters = { 
    "file": imgData, 
    "upload_preset": "mycode" 
}; 

xhttp.send(JSON.stringify(parameters)); 

resultierende Bild ist:

http://res.cloudinary.com/viksphotography/image/upload/v1490752341/irgvt7b3qwoug1vz7own.jpg 

Bitte beachten Sie, dass imgData base64

codiert ist

Antwort

1

Sie benötigen Formdata für das Hochladen der Datei zu verwenden:

const cloudName = 'your cloud name'; 
const unsignedUploadPreset = 'your unsigned upload preset'; 

// Upload base64 encoded file to Cloudinary 
uploadFile('data:image/gif;base64,R0lGODlhSAFIAf....'); 

// *********** Upload file to Cloudinary ******************** // 
function uploadFile(file) { 
    var url = `https://api.cloudinary.com/v1_1/${cloudName}/upload`; 
    var xhr = new XMLHttpRequest(); 
    var fd = new FormData(); 
    xhr.open('POST', url, true); 
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); 

    xhr.onreadystatechange = function(e) { 
    if (xhr.readyState == 4 && xhr.status == 200) { 
     // File uploaded successfully 
     var response = JSON.parse(xhr.responseText); 
     // https://res.cloudinary.com/cloudName/image/upload/v1483481128/public_id.jpg 
     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); 
    } 
    }; 

    fd.append('upload_preset', unsignedUploadPreset); 
    fd.append('tags', 'browser_upload'); // Optional - add tag for image admin in Cloudinary 
    fd.append('file', file); 
    xhr.send(fd); 
} 

Siehe vollständiges Beispiel here. Es wird ein kleines Michael Jordan Jumpman-Bild auf Ihr Konto hochgeladen.