Node wp-api create() not working after last update - wp-api

Recently wpapi updated and ther is no option to send posts or images via post api but maybe some errors in code. Here is half workable code for uploading images and post data to wordpress.
#!/usr/bin/env node
var moveFrom = __dirname+"/gallery/galleryfolder/year/";
var fs = require( 'fs' );
var path = require( 'path' );
// In newer Node.js versions where process is already global this isn't necessary.
var process = require( "process" );
// Loop through all the files in the temp directory
fs.readdir( moveFrom, function( err, files ) {
var moveFrom = __dirname+"/gallery/galleryfolder/year/";//setting up directory for file upload
if( err ) {
console.error( "Could not list the directory.", err );
process.exit( 1 );
}
files.forEach( function( file, index ) {
// Make one pass and make the file complete
var fromPath = path.join( moveFrom, file );
// var toPath = path.join( moveTo, file );
//starting getting filenames
fs.stat( fromPath, function( error, stat ) {
if( error ) {
console.error( "Error stating file.", error );
return;
}
if( stat.isFile() ){
console.log( "'%s' is a file.",moveFrom+file );
var fullpath=moveFrom+file;
var filename=file.replace('.jpg', '');//specifying the fullpath to the images on node server or in file system.
var WPAPI = require("wpapi");
var wp= new WPAPI({
endpoint: 'http://localhost/wordpress/wp-json/',
username: 'admibn',
password: '1234567890'
});
// let category=moveFrom.match('/[^/]*$/');
wp.posts().create({
title: filename,
content: '',
if ( err ) {
// handle err
}
}).then(function( post ) {
// Create the media record & upload your image file
var filePath = fullpath;
return wp.media().file( filePath ).create({
title: filename,
post: post.id
}).then(function( media ) {
// Set the new media record as the post's featured media
return wp.posts().id( post.id ).update({
featured_media: media.id
});
});
});
}
} );
} );
} );
The code is uploading images and posts text to the wordpress site.The first part of the code (node fs library)is working fine but the second i cannot even manage to debug or output the errors to console. I am a littele bit new to node.js. Please advice.

Solved. Thnx for the attention. Recently WPapi requires 2 plugins to be installed: JSON Basic Authentication and http://v2.wp-api.org/ wpapi plugin. I have edited code if someone else will be in search of batch wp uploading solution from pc(texts and images ). Also the post switcher plugin saves time that needed for custom post gateway.

Related

Preview appears but camera image not uploaded?

I am using https://www.dropzone.dev/js/ to upload images with the following script:
This is working if I upload an image. However when I capture an image with my phone (and someone else has had the same problem) although I see the preview on my .dropzone area the image never uploads. I have browsed my phone and actually don't see the image I have taken so am wondering if that is the problem but has anyone else managed to get images from a camera (where they're not saved) to upload with this script? Am I missing something?
$(".dropzone").dropzone({
url: base_url+'url/save',
acceptedFiles: 'image/*',
autoProcessQueue: false,
addRemoveLinks: true,
autoDiscover: false,
uploadMultiple: false,
init: function() {
var dzClosure = this;
$('#button[name="saveBtn"]').off('click').on('click',function(e){
e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
// Reload existing layer/view on datatable
setTimeout(function(){
MyAssets.ajax.reload(); // see notes at top
},500);
$('.modal:visible').modal('hide');
});
// When sending the data add our actual form contents too - note the formdata.append is crucial
dzClosure.on('sending', function (data, xhr, formData) {
var extra = getForm($('.modal:visible'));
formData.append(key,extra[key]);
});
// On removing files - if they are already there remove them!
dzClosure.on('removedfile',function(file) {
var params = {
fileContents: JSON.stringify(file),
assetID: $('.modal:visible').find('input[name="assetID"]').val(),
};
$.post(base_url+'url/remove',params);
})
// Preload existing image
dzClosure.addCustomFile = function(){
var thisFileBit = this;
// This is getting the SOURCE clicked VIEW link ...
// But its not ready yet
setTimeout(function(){
if (typeof $('#asset'+$('.modal:visible').find('input[name="assetID"]').val()).data('contents') != 'undefined'){
var origAsset = JSON.parse(atob($('#asset'+$('.modal:visible').find('input[name="assetID"]').val()).data('contents')));
} else {
var origAsset = {};
}
var file = {
accepted: true,
status: Dropzone.QUEUED,
size: origAsset.FileSize,
upload: {},
};
// Push file to collection
thisFileBit.files.push(file);
// Emulate event to create interface
thisFileBit.emit("addedfile", file);
// Add thumbnail url
if (origAsset.PublicImagePath != '' && typeof origAsset.PublicImagePath != 'undefined'){
thisFileBit.emit("thumbnail", file, origAsset.PublicImagePath);
}
// Add status processing to file
thisFileBit.emit("processing", file);
// Add status success to file AND RUN EVENT success from response
thisFileBit.emit("success", file,{
status: "success"
},false);
// Add status complete to file
thisFileBit.emit("complete", file);
},200);
}
// Includes test file above
dzClosure.on('addedfile',function (){
setTimeout(function(){
$('.dz-size span').data('dz-size');
$('.dz-details').remove();
$('.dz-image img').each(function(){
$(this).wrap('');
})
},1000);
});
dzClosure.addCustomFile();
}
});

Data is getting pasted twice (base64image and text) from excel to CKEditor

When I am trying to copy and paste the data from excel to ckeditor it is getting pasted twice as plain text and base64image. I need to paste it as base64image only. Screen shot is attached for reference.
I have resolved the problem using following solution
var editor = CKEDITOR.replace( 'editor1', {
extraPlugins : 'pastebase64'
});
editor.on( 'pluginsLoaded', function( event ){
var excelRegex = RegExp( '(schemas-microsoft-com\:office\:excel)', 'ig' );
// How to change image, dropped from local folder into CKEditor, from image file to base64 string with the help of CKEditor objects.
editor.on( 'paste', function( evt ) {
var testHtml = evt.data.dataTransfer.getData( 'text/html' , true);
if ( testHtml.search( excelRegex ) >= 0 )
evt.cancel();
});
});
Copy and paste duplicates images. I did the following:
I changed the file pastebase64 -> plugin.js..
I changed the following snippet:
line 34:
return Array.prototype.forEach.call(clipboardData.types, function (type, i) {
if (found) {
return;
}
if (type.match(imageType) ){ // || clipboardData.items[i].type.match(imageType)) {
readImageAsBase64(clipboardData.items[i], editor);
return found = true;
}
});
it worked for me....

Phonegap camera.getPicture() missing file extension and header data

I've been struggling on this for a while.
When I upload an image in a phonegap application with camera.getPicture() and ft.upload() the image is uploaded without file extension. I read it was because of a cache thing, providing a link to the actual file entry or something.
It was annoying me but I moved on since the image was uploaded fine on my server and displayed fine too even without file extension.
But today, we figured images were sometime rotated by 90°.
I instantly made the connection between the missing part of the image data and this issue, and I guess (not sure) I am right on this point.
I read image rotated by 90° could be caused by missing header meta data, so I guess not only the file extension were missing after all..
Could someone explain me what am I missing in the code and what to do or in which direction to look ? That would be awesome.
Here is part of my code (I can give you more if needed)
navigator.camera.getPicture(function(uri) {
try {
var imageURI = uri;
...
var ft = new FileTransfer();
ft.upload(imageURI, "some_script.php", function(r) {
...
Note:The image stored in database seems fine, the issue happens when the image is displayed in an tag.
Here an example of file getting rotate once uploaded (I added manually the .jpg extension so I could upload it on noelshack otherwise not able to). As you can see, the link to image is OK but once in tag it gets rotated
http://image.noelshack.com/fichiers/2015/41/1444168922-35-1444166605.jpg
http://jsfiddle.net/c3ybkqt8/
tl;dr
How to upload an image file entirely with phonegap including file extension & metadata header and not only a sort of cached file entry.
iOS Code
function capturePhoto() {
navigator.camera.getPicture(uploadPhoto, onFail, {
quality: 50,
// allowEdit: true,
correctOrientation: true,
destinationType: Camera.DestinationType.FILE_URL,
// destinationType: Camera.DestinationType.DATA_URL
sourceType: Camera.PictureSourceType.CAMERA
}
);
}
// function onPhotoDataSuccess(imageData) {
// localStorage.setItem("ImageData",imageData);
// localStorage.setItem("captureImgFlag",captureImgFlag);
// window.location = 'profileUserImgUploadInGallary.html';
// }
function onFail(message) {
// alert('Failed because: ' + message);
}
function uploadPhoto(imageURI){
console.log(imageURI);
spinnerplugin.show();
var UserId = localStorage.getItem('UserId');
// imgPostGallary
// var img = document.getElementById('imgPostGallary');
// var imageURI = img.src;
// var imageURI = imageData;
// img.src = imageURI;
// var ImageDataUp = localStorage.getItem('ImageDataUp');
// var imageURI = ImageDataUp;
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://XYZ/uploadimg?user_id="+UserId+""), winGallary, fail, options);
console.log(ft.upload);
}
function winGallary(rGallary) {
console.log("Code = " + rGallary.responseCode);
console.log("Response = " + rGallary.response);
console.log("Sent = " + rGallary.bytesSent);
spinnerplugin.hide();
window.location = 'profileUserImgUploadInGallary.html';
}
function fail(error) {
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
Hello, here is full example it's working for me capturing photos and set in image tag and upload that photos on server. and still you have facing any problem message me.
<img id="profileImageId">
<script type="text/javascript">
var profileImage = '';
function profileCapturePhotoEdit() {
navigator.camera.getPicture(profileonPhotoDataSuccess, onFail, {
quality: 50,
// allowEdit: true,
correctOrientation: true, // using this your image not roted 90 degree
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA }
);
}
function profileonPhotoDataSuccess(imageData) {
localStorage.setItem("imageDataProfile","data:image/jpeg;base64," + imageData);
var imageDataProfile = localStorage.getItem("imageDataProfile");
document.getElementById('profileImageId').src = imageDataProfile;
}
function onFail(message) {
// alert('Failed because: ' + message);
}
</script>
<!-- uploadProfileImage -->
<button onclick="uploadProfileImage();">
Upload Profile Image
</button>
<script type="text/javascript">
function uploadProfileImage() {
var UserId = localStorage.getItem('UserId');
var img = document.getElementById('profileImageId');
var imageURI = img.src;
var options = new FileUploadOptions();
options.fileKey="file"; // your file key in your .php file change here
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg"; // your extension
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://XYZ?user_id="+UserId+""), winProfile, failProfile, options);
}
function winProfile(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
// alert('Send success');
}
function failProfile(error) {
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
</script>

Dropzone.js and full path for each file

I'm trying to recreate the folder structure of dropped files/folder with Dropzone.js.
Is there a way to have access to the full path of each file, so that the directory structure can be re-created on the php side?
This is a simple way you can send additionally full paths of all files which are in some folder(s):
dropzone.on("sending", function(file, xhr, data) {
// if file is actually a folder
if(file.fullPath){
data.append("fullPath", file.fullPath);
}
});
you can use a file reader for it, I did it in angular 5:
onFilesAdded(files: File[]) {
console.log(files);
this.dropzone.reset();
files.forEach(file => {
const reader = new FileReader();
let content;
reader.onload = (e: ProgressEvent) => {
content = (e.target as FileReader).result;
console.log(content);
};
this.previewImage(file).then(response => {
const imageItem = new FileItem(
response,
content,
);
let imagesComponentItems = this.store.value.imagesComponentItems;
imagesComponentItems = [...imagesComponentItems, imageItem];
this.store.set("imagesComponentItems", imagesComponentItems);
this.hasImages();
});
});
}

Import Zip Files

I'm using OBJ format, but OBJ is too heavy to download it, for that reason, I would like to upload the OBJ files in Zip, then, the viewer unzip it and call the function OBJLoader.
Do you know what's the best way to do it?
Thanks,
Rafa
Problem solved by :
1) add jszip script to your page
2) Goto OBJMTLLoader.js (about line 33) and place these 10 lines to uncompress the zip (assuming that the file.zip contains only the file.obj) inside the loader.load function
loader.load( url, function ( text ) {
if (url.split('/').pop().split('.')[1] == 'zip'){
//- Uncompress url e.g. http:// .... / PTERO.zip -> PTERO.obj -
// zip should contain only one file !
// uncompression object
var new_zip = new JSZip();
// uncompress
new_zip.load(text);
// the single file name convention
filename = url.split('/').pop().split('.')[0] + ".obj";
// get the file content as text
text = new_zip.file(filename).asText();
}
//--------------------------------------------
var object = scope.parse( text );
3) Add these 2 lines in the XHRLoader in Three.js so that it loads binary when extension is zip:
THREE.XHRLoader.prototype = {
constructor: THREE.XHRLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var cached = scope.cache.get( url );
if ( cached !== undefined ) {
if ( onLoad ) onLoad( cached );
return;
}
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
// ---------- for zipped obj ------------
if ( url.split('.').pop() == 'zip')
request.responseType = "arraybuffer";
//--------------------------------------
request.addEventListener( 'load', function ( event ) {
scope.cache.add( url, this.response );
...
Beyond what is the best solution, it's really senseless that you can't pass a buffer to the loader instead of a URL. I needed that too, so I used #jimver's answer but changing the JSZip methods because they were deprecated. Use this instead (in my case I made the changes on file STLLoader.js because I was working with STL files, but this applies to any loader):
THREE.STLLoader.prototype = {
constructor: THREE.STLLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var loader = new THREE.XHRLoader( scope.manager );
loader.setResponseType( 'arraybuffer' );
loader.load( url, function ( text ) {
if (url.split('/').pop().split('.')[1] == 'zip') {
JSZip.loadAsync(text)
.then(function (zip) {
return zip.file(Object.keys(zip.files)[0]).async("arrayBuffer");
})
.then(function success(text) {
onLoad( scope.parse( text ) );
}, function error(e) {
console.log(e);
});
}
else {
onLoad( scope.parse( text ) );
}
}, onProgress, onError );
},
// rest of the code
I would try using jszip
JSZipUtils.getBinaryContent('path/to/objzipped.zip', function(err, data) {
if(err) {
throw err; // or handle err
}
var zip = new JSZip(data);
var objData = zip.file("objfile.obj").asText();
var object3D = new OBJLoader().parse(objData); // ...
});
In case you really want to use zip in the browser,
I think you could go with unzip a downloaded file with zip.js and parse the result with OLBJLoader.parse.
Decoding gzip is built into the browsers. You dont need any client side code at all. All you need to do is make sure the server is setting the right MIME type.
See: What 'Content-Type' header to use when serving gzipped files?

Resources