I am trying to upload images from Gmail email attachments to Wordpress with Google Apps Script, using Wordpress REST API.
I am successfully able to create the media file, but it is always blank so the actual image data is not actually transferring.
I was able to authenticate successfully, and the Wordpress credentials definitely have upload permissions. A media attachment is created in Wordpress when I run my code, but it is blank and not the actual image. I've tried sending the payload as a Blob, as a string Base64 encoded, as bytes, using getAs("image/jpeg") and many other ways of grabbing the file data.
uploadImage();
function getImage(){
var email = GmailApp.search("subject:(EMAIL WITH IMAGE)")[0].getMessages[0];
var attachment = email.getAttachments()[0];
var blob = att.copyBlob();
return blob;
}
function uploadImage(){
// ... SUCCESSFUL AUTHENTICATION OCCURS
var postPayload = {
"file": getImage()
}
var params = {
"payload": JSON.stringify(postPayload),
"contentType": "image/jpeg",
"method": "POST",
"headers" : { "Authorization" : "Bearer XXXXXXXXXXXXXXXXXXXX",
"Content-Disposition": "attachment; filename=test.jpg"}
};
var response = UrlFetchApp.fetch('http://mydomainname.com/wp-json/wp/v2/media/', params);
return response
}
I receive a valid JSON response of the created attachment, and I would expect the image to upload to Wordpress. However, the attachment created is a blank/empty file and not the image.
If getImage()
returns the blob of the image, how about this modification?
Please modify the object of params
as follows. Before you run the script, please confirm whether att
of att.copyBlob()
is attachment
.
"payload": JSON.stringify(postPayload),
"payload": getImage(),
postPayload
is not used."payload": getImage()
can be used. But if an error occurs, please try to modify it to "payload": getImage().getBytes()
.If this was not the solution of your issue, I apologize. If an error occurs, please show the error message.