User Imports a .stl file in js which has to be saved into database or server folder. Using javascript we are importing file from js, but since we cannot save it in our server, so im using ajax to send the file from js to php. So that from php we can save it in our folder.
Below is code in which file is being fetched, but that file is not going to php. Please help me how to send a stl file from js to php
Stage.prototype.handleFile = function(file) {
this.importingMeshName = file.name;
this.importEnabled = false;
var model = new Model(
this.scene,
this.camera,
this.container,
this.printout,
this.infoBox,
this.progressBarContainer
);
model.isLittleEndian = this.isLittleEndian;
model.vertexPrecision = this.vertexPrecision;
model.import(file, this.displayMesh.bind(this));
var form_data = new FormData();
form_data.append("file", document.getElementById('file').files[0]);
jQuery.ajax
({
url: 'saveinjs.php',
type: "POST",
data: {user:1, postdata:form_data},
contentType: false,
cache: false,
processData: false,
success:function(data)
{
$('#uploaded_image').html(data);
alert(data);
console.log(data);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
};
This is php code to fetch the file and save in our folder
<?php
if(isset($_POST['user'])){
echo '123';
if($_POST["file"]["name"] != '')
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ;
}
}
?>
</div>
You can use javascript File
api to read content in base64 format. Then in your back end code you can decrypt to get actual content. Below is the frontend code for handling the file
function handleFile(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
var data = {data: reader.result};
// You can post data object to server in json format
// Make Ajax request
};
reader.onerror = function (error) {
console.log('Error: ', error);
// Handle error
};
}
var file = document.getElementById('file').files[0];
handleFile(file);
And using base64_decode
function in php you can decode base64 string, http://php.net/manual/en/function.base64-decode.php
</div>