Emulate file uploading forms with JavaScript - javascript

I dynamically generate svg markup on client side and convert it to a data-url for downloading purposes. This procedure works fine and generates a valid svg file.
Besides I have a Java Servlet which takes an uploaded svg file and converts it to pdf. When I take a downloaded svg file from above and upload it through a standard HTML form this Servlet works absolutely fine.
I just want to combine those two parts by sending the generated svg without even saving it before. I already tried to send the data as base64 string like that:
reader.readAsDataURL(blob);
reader.onloadend = function() {
base64data = reader.result;
console.log(base64data );
form['data'].value = base64data;
form.submit();
}
But this doesn't seem to work. Are there any ways of emulating a file upload with JavaScript?

You should use FormData object:
$('form').submit(function(){
/**** creating blob object
.....
****/
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
base64data = reader.result;
var fd = new FormData(this);
fd.append('file', base64data, 'file_data'); // field_data - "Optional" param, it means The filename reported to the server
fd.append('other_field', fieldvalue);
$.ajax({
type: 'POST',
url: '/upload.php',
data: fd,
processData: false,
contentType: false
}).done(function(data) {
console.log(data);
});
}
});

Related

upload canvas image to Laravel

I have a canvas image generated by some JS on my page that I'm trying to upload to my server using Laravel, my controller code:
public function imageUploadAPI(Request $request)
{
$imageName = time().'.'.$request->image->getClientOriginalName();
$request->image->move('/home/XXXXX/storage/app/public/images/'.$request->project_id.'/'.$request->report_id.'/', $imageName);
return response()->json(['success'=>['You have successfully upload image.'],'image'=>[$request->project_id.'/'.$request->report_id.'/'.$imageName]]);
}
Im trying to send in as a blob but it did NOT work, any ideas?
my code:
function uploadImage() {
var canvas = document.getElementById('snapshot');
canvas.toBlob((blob) => {
const newImg = document.createElement('img');
const url = URL.createObjectURL(blob);
newImg.onload = () => {
URL.revokeObjectURL(url);
};
var formdata = new FormData($("#addForm")[0]);
formdata.append('image', url);
$.ajax({
url : "/api/image-upload",
type: "POST",
data : formdata,
processData: false,
contentType: false,
success:function(data){
console.log(data.image);
},
error:console.log('Error'),
});
});
}
One thing i know is laravel need file instance to upload image using laravel storage helpers so check if your upload is file instance or not. Here is a solution if your uploaded file is base64 and you want to change it to file instance How to convert base64 image to UploadedFile Laravel

SEND BLOB VIDEO (FROM WEBRTC) TO A MYSQL SERVER IN PHP

I have tried using some code to get blob uploaded to server, but this code has not functioned as intended. need help in finding where the error is and perhaps how to upload blob video to MySQL server.
The js code I used is
var blob = URL.createObjectURL(recorder.getBlob());
var fd = new FormData();
fd.append('fname', 'test.mp4');
fd.append('data', blob);
$.ajax({
type: 'POST',
url: '../../application/controllers/upload.php',
data: fd,
processData: false,
contentType: false
}).done(function(data) {
alert(data);
});
Then this is the PHP code I tried
foreach(array('video', 'audio') as $type) {
if (isset($_FILES["${type}-blob"])) {
echo 'uploads/';
$fileName = $_POST["${type}-filename"];
$uploadDirectory = 'uploads/'.$fileName;
if (!move_uploaded_file($_FILES["${type}-blob"]["tmp_name"], $uploadDirectory)) {
echo(" problem moving uploaded file");
}
echo($fileName);
}
}
Once I am able to get this working I can be able to insert the data into MySQL database
Thank you for helping
you placed your blob into your formdata OBJECT and called it data
fd.append('data', blob);
So when that gets to PHP is will be placed in
$_FILES['data']
Just like as if you had done
<input type="file" name="data">

How to upload a file with ajax and move it with PHP?

I'm using javascript to get the filepath but it returns C:\fakepat\ fileName, then I replace the fakepath to get the filename only. Then ajax to php. And execute this line:
copy("filename", $targetPath);
It returns this error no directory or file.
PHP is executed on server-side, therefor it has no access to your client-side file.
To transmit the file from client to server using ajax I recommend wrapping a form around your upload-button. After submitting the XHR you can access the file in PHP via the $_FILES variable and move it where ever you want:
HTML
<form>
<input type="file" id="upload" onchange="javascript:uploadFile()" />
</form>
JS
function uploadFile() {
var formData = new FormData(); // using XMLHttpRequest2
var fileInput = document.getElementById('upload');
var file = fileInput.files[0];
formData.append("uploadfile", file);
request.send(formData);
}
PHP
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['uploadfile']['name']);
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $uploadfile)) {
// upload succeeded
} else {
// upload failed
}
in ajax you can write this
var form_data = new FormData();
var file_data1 = $('#file').prop('files')[0];
form_data.append('file', file_data1);
$.ajax({
url: 'assets/addEdi.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (php_script_response) {
$('#res').html(php_script_response);
}
});
#Toltis Because of the fakepath, you should upload via javascript.
This it the html:
<input type="file" id="file" onchange="upload(event)" />
<img src="" id="img" />
<textbox id="hidden_box" name="hidden_box" style="visibility: hidden;"></textbox>
Then the Js:
function upload(e) {
var input_file = document.getElementById('file');
var hidden = document.getElementById('hidden_box');
var fr = new FileReader();
fr.readAsDataURL(input_file.files[0]);
fr.onloadend = function(e) {
var img_tag = document.getElementById('img');
dataUrl = e.target.result;
img_tag = dataUrl
hidden.innerHTML = dataUrl
}
}
Then you can target the contents of the hidden box in php. Break it on the (,) and then decode the remaining string - base64_decode - and then save it to a file.
The real file name, you already know how to get it.

How to save my generated javascript pdf file to my server's filesystem?

I'm using pdfmake to create my pdf and while it allows the user to open the pdf directly or download it to their computer, I'm not sure how I would go about generating the pdf and saving it to my server's file system.
From what I understand, there are plenty of security measures not allowing javascript to save data to file(s), so would sending it to my php backend be the only choice ? and how would i go about doing that ?
Thanks !
(untested)
PHP:
<?
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data,
echo ($decodedData);
$filename = "test.pdf";
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>
JS:
var docDefinition = {
content: 'This is an sample PDF printed with pdfMake'
};
pdfMake.createPdf(docDefinition).getBuffer(function(buffer) {
var blob = new Blob([buffer]);
var reader = new FileReader();
// this function is triggered once a call to readAsDataURL returns
reader.onload = function(event) {
var fd = new FormData();
fd.append('fname', 'test.pdf');
fd.append('data', event.target.result);
$.ajax({
type: 'POST',
url: 'upload.php', // Change to PHP filename
data: fd,
processData: false,
contentType: false
}).done(function(data) {
// print the output from the upload.php script
console.log(data);
});
};
// trigger the read from the reader...
reader.readAsDataURL(blob);
});
Upload and receive code from How can javascript upload a blob?.

Im not able to decode my file passed from JAVASCRIPt to PHP

I am encoding and passing a file (word document) to php.How can I read this and write to a file?
I have submit button.On submit, I am passing an ajax.Before that, Iam encoding the file with file reader.On submit button, an event 'handleFileSelect' is trtiggered.The file is read as dataurl and sent to php via ajax.
I am able to get the data as encoded.If the file is a text, i am also able to decode .But
its not able to get the contents of a word file.If I decode
How would I do this?
My code :
//File Convertion--Function to convert images to base 64 encoded format
function handleFileSelect(objEvent) {
var strFiles = objEvent.target.files; // FileList object
strInput = document.getElementById('uploaded_file');
strFile = strInput.files[0];
strFiletype=strFile.type;
strFileSize=strFile.size;alert(strFiletype);
strFiletype=strFiletype.split("/");
//Checking wheter the uploaded file is image or not
if(strFiletype[0]!='image') {
for (var i = 0, f; f = strFiles[i]; i++) {
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
strGlobalImageData=e.target.result;
};
})(f);
reader.readAsDataURL(f);
}
} else {
alert("NOT A DOC");
}
}
//ajax call to send files to php
var app = 'contact.php';
$.ajax({
url: app,
async: false,
type:"POST",
data : "file="+strGlobalImageData,
dataType: "jsonp",
contentType: 'application/x-www-form-urlencoded',
processData:false,
jsonp: "jsoncallback",
success: function(html) {
alert("Thank you. We will be in touch with you");
},
error: function(){
alert("Thank you. We will be in touch with you");
}
});
//Php side--contact.php
<?php
$files=base64_decode($_POST['file']);
If I decode, I am getting a binary format of the word file
The issue was with character replacing.We need to replace befor decoding the data.The exact code is shown below:
In Php,
$files=trim($_POST['file']);
$strEncodedData= str_replace(' ','+',$files);
$strFilteredData = explode(',',$strEncodedData);
$strDecodedData= base64_decode($strFilteredData[1]);
$arrFiles = explode(",",$files);
file_put_contents("myfile.doc",$strDecodedData);
This content will be written into file "myfile.doc".
Thank you for all effort made by my friends

Categories