omrips / viewstl

Viewstl Javascript plugin - STL/OBJ 3D files Viewer by viewstl.com
MIT License
193 stars 48 forks source link

Downloading vsb to Webserver #12

Open JoaZaech opened 3 years ago

JoaZaech commented 3 years ago

I can't download a tmp vsb file to the webserver to use it. Surely I can download it, but that would be client side. The vsb is essential for the Webserver to display windows for example etc. a preview for the user. In addition, changeing the color of the model results in a reload of the website which then wipes the localfile in the upload. If I could make a tmp copy of the vsb file I can display it anyway.

omrips commented 3 years ago

At the moment, you can use "get_vsb" - it returns a Javascript object, not suitable to upload to the server yet. I should create a function to store the vsb file on blob var or something ... but for now, you'll have to convert the vsb object into blob by yourself - with the code below (and then upload the blob into the server and save it there as a vsb file):

var vsb=_this.get_vsb();
var zip = new JSZip(); //JZip library

zip.file("json_data.vsj", JSON.stringify(vsb.vsj).split(",null").join(""));
Object.keys(vsb.files).forEach(function(key)
{
   var curr_filename=stl_viewer.get_model_filename(vsb.vsj.models[stl_viewer.models_ref[vsb.files[key].id]], true, true);
   zip.file(curr_filename, vsb.files[key].bin);
});

zip.generateAsync({type:"blob"})
.then(function(content)
{
   var blob = new Blob([content], {type: "application/zip"});
   /* upload to the server code */
});
omrips commented 3 years ago

You can now use a new method get_vsb_blob, which returns a "vsb" file as blob (binary large object). Then you can do whatever you want with it - like sending it do server (and then to save it on file).

example code (sends the blob to server side script 'upload.php'):

stl_viewer.get_vsb_blob().then(function (content)
{
    console.log(content);
    fetch('upload.php', {method:"POST", body:content})
        .then(response =>
        {
            if (response.ok) {console.log("good");}
            else throw Error('Server returned ${response.status}: ${response.statusText}');
        })
        .catch(err =>
        {
            alert(err);
        });     
});

code at the server side (upload.php):

<?php    
    // gets entire POST body
    $data = file_get_contents('php://input');
    // write the data out to the file
    $fp = fopen("my_vsb_file.vsb", "wb");

    fwrite($fp, $data);
    fclose($fp);
?>