The post shows a template about how to send file to our remote server.
We need to prepare html page, javascript and php script.

HTML Page

Write a web page and import front.js that contains submit event.

front.html:

<!DOCTYPE html>
<html>
<body>

<div key="uploadMeshContent" id="content">
<input type="file" id="uploadMesh" name="uploadMesh"/>
<progress id="progressMesh" value="1" max="100"></progress> <br/>
<input id="subSTLButton" type="button" value="Submit" name="submit" />
</div>

<script type="text/javascript" src="front.js"></script>
<script>
    document.getElementById('subSTLButton').onclick = subMesh;
</script>
</body>
</html>

The rendering result:

JS code

We will change progress bar as sending file to remote server.
Start the next task when finish sending.

front.js:

function subMesh(){
    var files = document.getElementById("uploadMesh").files;
    if( files === undefined || files === "" )
    {
        alert("please choose file");
        return false;
    };

    var form = new FormData();
    form.append("fileObj", files[0]);
    var xmlRequset = new XMLHttpRequest();
    var url = "./uploadFile.php";
    xmlRequset.open("post", url, true); 
    xmlRequset.upload.onprogress = progressFunctionMesh;
    xmlRequset.onload = uploadCompleteMesh;
    xmlRequset.onerror = uploadFailedMesh;
    xmlRequset.send( form );
}

function progressFunctionMesh(event)
{
    var value = Math.round(event.loaded / event.total * 100);
    console.log( value );
    document.getElementById("progressMesh").value = value;
}

function uploadCompleteMesh(evt) {
    var text = evt.target.responseText;
    console.log( text )
    if( text.substr( 0, 4 ) === "url:" )
    {
        var url = text.substr( 4, text.length );
        console.log( url );
        // to do something
    }
}

function uploadFailedMesh(evt) {
    alert("failed to upload file!");
}

PHP Script

Write php script to receive the uploaded file in server side.
uploadFile.php:

<?php
$Debug = false;
if( $Debug )
{
    ini_set('display_errors',1);
    error_reporting(E_ALL);
}

function CheckFolder( $filePath )
{
    $cmdStr = __DIR__ . '/checkFolder.py' . ' ' . $filePath;
    $handle = popen( $cmdStr , 'r' );
    if( false == $handle )
    {
        echo "failed: " . $cmdStr . "\n";
    }
    else
    {
        //echo "'$handle'; " . gettype($handle) . "\n";
        pclose( $handle );
    }
}

$fileAttr = $_FILES['fileObj'];

set_time_limit ( 0 );
$target_dir = $_SERVER["DOCUMENT_ROOT"] . "/projects/SimpleTools/3DModelEditor/build_wasm/upload";
$target_basename = basename($fileAttr["name"]);
$target_basename = str_replace( " ", "_", $target_basename ); //remove blank
$upload_file = $target_dir . "/" . $target_basename;
$uploadOk = 1;
$fileType = strtolower(pathinfo($upload_file,PATHINFO_EXTENSION));

CheckFolder( $upload_file );

// check uploads folder
if( !file_exists( $target_dir ) )
{
    if( mkdir( $target_dir ) )
    {
        if( $Debug )
        {
            echo "Create upload folder successfully.\n";
        }
    }
    else
    {
        echo "failed to create folder: " . $target_dir . "\n";
        $uploadOk = 0;
    }
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0)
{
    echo "Sorry, your file was not uploaded.\n";
    exit( -1 );
// if everything is ok, try to upload file
}
else
{
    if (move_uploaded_file($fileAttr["tmp_name"], $upload_file))
    {
        if( $Debug )
        {
            echo "The file ". $upload_file . " has been uploaded.\n";
        }
        echo "url:".$upload_file;
    }
    else
    {
        echo "Sorry, there was an error uploading your file: \n";
        echo "  ".$fileAttr["tmp_name"]."  =>  ".$upload_file . "\n";
        exit( -1 );
    }
}
?>

Python Script For Folder Check

We use a python script to clear server folder if the uploaded files are too big. Make sure the server’s disk is enough.
checkFolder.py:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import sys
import shutil

def getFolderSize( start_path ):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            filePath = os.path.join(dirpath, f)
            # skip if it is symbolic link
            if not os.path.islink(filePath):
                total_size += os.path.getsize(filePath)
    return total_size

if __name__ == '__main__':
    filePath = sys.argv[1]
    # clear big folder: upload
    folder = filePath[0:filePath.rindex( "/" )]
    if getFolderSize( folder ) > 1024*1024*100:
        shutil.rmtree( folder )
        os.mkdir( folder )
Categories: Web

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments

Computer Number Terms
: You can use the tool to get different expressions of color, disk space and number.

X
A prohibited operation
0
Would love your thoughts, please comment.x
()
x