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?
Related
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();
}
});
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....
I'm trying to add a plugin to set a default URL when adding a link.
I followed the instructions here:
https://apostrophecms.org/docs/tutorials/howtos/ckeditor.html
And I ended up with:
// lib/modules/apostrophe-areas/public/js/user.js
apos.define('apostrophe-areas', {
construct: function(self, options) {
var superEnableCkeditor = self.enableCkeditor;
self.enableCkeditor = function() {
superEnableCkeditor();
CKEDITOR.plugins.addExternal('defaulturl', '/modules/my-apostrophe-areas/js/ckeditorPlugins/defaulturl/', 'plugin.js');
};
}
});
and this is my apostrophe-areas/public/js/ckeditorPlugins/defaulturl/plugin.js
CKEDITOR.on( 'dialogDefinition', function( ev ) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
if ( dialogName == 'link' ) {
var infoTab = dialogDefinition.getContents( 'info' );
var urlField = infoTab.get( 'url' );
urlField[ 'default' ] = 'www.example.com';
}
});
However, this is not working for me, I tried to do what is suggested here:
Ckeditor plugin configuration not working
But it doesn't worked.
What I've tried and worked was to append the plugin.js file at the end of the plugin.js of the split plugin at the apostrophe-area folder, but I think this is not the correct way to go
Thanks!
I think you can solve the issue two ways:
1. If you want to keep the external plugin file:
Wrap your code according to the API, see e.g. https://sdk.ckeditor.com/samples/timestamp.html and the plugin it references https://sdk.ckeditor.com/samples/assets/plugins/timestamp/plugin.js for an example. You need to use CKEDITOR.plugins.add( 'defaulturl', { init: ... }) in your plugin.js. Not sure if there is anything special to do otherwise as you want to modify the behavior of a CKEDITOR core plugin. That's why it would go with the next option...
2. If you don't need the extra plugin.js:
You can also replace the CKEDITOR.plugins.addExternal() call with the contents of your plugin.js file. I did this to modify the default link target to be _blank:
// /lib/modules/apostrophe-areas/public/js/user.js
'use strict';
// See https://apostrophecms.org/docs/tutorials/howtos/ckeditor.html and
apos.define('apostrophe-areas', {
construct: function(self, options) {
var superEnableCkeditor = self.enableCkeditor;
self.enableCkeditor = function enableCkeditor() {
superEnableCkeditor();
// https://docs.ckeditor.com/ckeditor4/latest/guide/dev_howtos_dialog_windows.html
CKEDITOR.on('dialogDefinition', function redefineDialog(ev) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
if (dialogName === 'link') {
var targetTab = dialogDefinition.getContents('target');
var targetField = targetTab.get('linkTargetType');
targetField.default = '_blank';
}
});
};
}
});
Good luck!
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.
Hi Im doing a Windows 8 Javascript App, y what to know how to get a file witch name is example2.dat from C:\Users\Me\Pictures\thifolder I tried using Windows.Storage.StorageFile.getFileFromPathAsync("C:\Users\Me\Pictures\thisfolder");
but it didnt work since i have another files like example1.dat, example3.dat example.jpg etc.
Hope i made my self clear, thanks in advance
Here is my code so far
function here() {
var getJsonStringAsync = function () {
return Windows.Storage.StorageFile.getFileFromPathAsync("C:\Users\Me\Pictures\thisfolder")
//Also tried this
//return Windows.Storage.KnownFolders.picturesLibrary.getFileAsync(u_u + "_" + u + "_" + ".dat")
.then(function (file) {
return Windows.Storage.FileIO.readTextAsync(file);
});
};
getJsonStringAsync().then(function (text) {
document.getElementById("line").innerHTML = text;
});
}
The correct way to read a file in the pictures library is this:
(don't forget to declare in the manifest of your app the access to the picturesLibrary)
var getJsonStringAsync = function () {
var picturesLibrary = Windows.Storage.KnownFolders.picturesLibrary;
return picturesLibrary.getFolderAsync("thisfolder").then(function (folder){
return folder.getFileAsync("example2.dat").then(function (file) {
return Windows.Storage.FileIO.readTextAsync(file);
});
});
};
In JavaScript, here is how to play "song.mp3" which is in the music library:
Html:
<audio id="player1">Your browser does not support audio </audio>
JavaScript:
var ml = Windows.Storage.KnownFolders.musicLibrary;
ml.getFileAsync("song.mp3").then(function (file) {
// its a storage file, so create URL from it
var s = window.URL.createObjectURL(file);
player1.setAttribute("src", s);
player1.play();
//});
});