How to create file from 'blob:http://' url - php

I have blob:http://unifiedmain.localhost.com/a4580f39-8f9d-4e8c-8e4b-02a6bd2df3df url and i want to create actual file file from this.
I've used
PHP code :
file_put_contents('E:\www\nginx\html\unifinedmainsite\123.mp3', file_get_contents($_REQUEST['id']));.
javascript code:
var xhr = new XMLHttpRequest;
xhr.responseType = 'blob';
xhr.onload = function() {
var recoveredBlob = xhr.response;
var reader = new FileReader;
reader.onload = function() {
jQuery.ajax({
type: "POST",
url: BASEURL+"/index.php?saveFileInSession=true",
data: "id="+reader.result,
success: function(response) {
console.log(response);
}
});
};
reader.readAsDataURL(recoveredBlob);
};
xhr.open('GET', 'blob:http://unifiedmain.localhost.com/a4580f39-8f9d-4e8c-8e4b-02a6bd2df3df');
xhr.send();
file is generating with actual size but i can not open it ,what is i am doing wrong?
Do i have to pass some header or something?so that i can play my saved/uploaded .mp3 file?
please help.

Related

Save generated PDF file on the server with jsPDF and PHP

I'm trying to save the generated PDF file with JSPDF plugin into the server instead of being saved on the client side, the javascript part that handles the JsPDF is this:
<script type="text/javascript">
(function(){
var
form = $('.form'),
cache_width = form.width(),
//cache_height = form.height(),
a4 =[ 595.28, 841.89]; // for a4 size paper width and height
$('#create_pdf').on('click',function(){
$('body').scrollTop(0);
createPDF();
});
//create pdf
function createPDF(){
getCanvas().then(function(canvas){
var
img = canvas.toDataURL("image/png"),
doc = new jsPDF({
unit:'px',
format:'a4'
});
var imgWidth = 220;
var pageHeight = 295;
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
var doc = new jsPDF('p', 'mm');
var position = 0;
doc.addImage(img, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(img, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
var blob = doc.output('blob');
var formData = new FormData();
formData.append('pdf', blob);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
dataType: 'text',
cache: false,
processData: false,
contentType: false,
success: function(response){
alert(response);
console.log(response)
},
error: function(err){
alert(err);
console.log(err)
}
});
});
}
// create canvas object
function getCanvas(){
form.width((a4[0]*1.33333) -80).css('max-width','none');
return html2canvas(form,{
imageTimeout:2000,
removeContainer:true
});
}
}());
</script>
the upload.php file should move the generated pdf file or its content to the Uploads folder but it seems that the $_FILES['data'] is empty
<?php
if(!empty($_FILES['data'])) {
// PDF is located at $_FILES['data']['tmp_name']
$content = file_get_contents($_FILES['data']['tmp_name']);
//echo $content;
$location = "uploads/";
move_uploaded_file($_FILES['data']['tmp_name'], $location.'random-name.pdf');
} else {
throw new Exception("no data");
}
the response I get back from Ajax is "Notice: Undefined index: data ".
Thanks in advance for any help.
I finally got it to work using this code:
var pdf = btoa(doc.output());
var file_name = $('#id').val();
//var file_name = 'hello world';
$.ajax({
method: "POST",
url: "upload.php",
data: {data: pdf, filename: file_name},
}).done(function(data){
// alert(data);
console.log(data);
});
and on the server side upload.php like this:
if(!empty($_POST['data'])){
$data = base64_decode($_POST['data']);
$fileName = $_POST['filename'];
file_put_contents( "uploads/".$fileName.".pdf", $data );
} else {
echo "No Data Sent";
}
exit();

How to rewrite Ajax without using JQuery for my code

Hi I am currently trying to save an image on my canvas to my database, but my code uses jQuery of which I am not allowed to. Can someone please help me with an equivalent of this ajax command without using JQuery, here is my code:
document.getElementById('save').addEventListener('click', function()
var canvas = document.getElementById("canvas");
var dataUrl = canvas.toDataURL("image/png");
$.ajax(
{
type: "POST",
url: "../webcam/save_image.php",
data: {image: dataUrl}
})
.done(function(respond){console.log("done: "+respond);})
.fail(function(respond){console.log("fail");})
.always(function(respond){console.log("always");})
});
You can use Native XMLHttpRequest Objects to accomplish this. I believe your code should look something like this, I haven't tested it though, so you will need to tweak it somewhat I'm sure.
document.getElementById('save').addEventListener('click', function()
var canvas = document.getElementById("canvas");
var dataUrl = canvas.toDataURL("image/png"), xhr = new XMLHttpRequest();
xhr.open('POST', '../webcam/save_image.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200 && xhr.responseText !== dataUrl) {
console.log('fail');
}
else if (xhr.status !== 200) {
console.log('fail');
}
};
xhr.send(encodeURI('url=' + dataUrl);
Reference: https://blog.garstasio.com/you-dont-need-jquery/ajax/#posting

Ajax image upload not working as expected

I am trying to send an image via JavaScript after displaying the preview on the screen, I refuse to use Dropzone, Plupload or any JavaScript library, because I just want a simple functionality.
var finput;
var fileReader;
var fd; //formdata...
$(function(){
fileReader = new FileReader;
fileReader.onload = function(e) {
var img = document.createElement("img");
img.src = fileReader.result; //display the image on the screen...
img.height = 200;
$('#pimgbox').html(img);
//enable the image button... // $('#pimagebox').html(img);
$('#pimgbtn').removeAttr('disabled', 'disabled').removeClass('btn-alert').addClass('btn-primary');
}
});
and when you click on the submit button
$('#pimgbtn').bind('click', function(e){
//initialize the formdata...
fd = new FormData(); //initialize the formdata..
fd.append('pimgupl', finput.files[0]); //s
//alert(fd);
$('#pimgldr').css('display','block');
$(this).attr('disabled', 'disabled').removeClass('btn-primary').addClass('btn-alert')
if(fileReader.result != null){
////////////// beginning of ajax call...
var settings = {
type: "POST",
url: "/user/setprofilepix",
data: fd
}; //end of setting..
$.ajax(settings)
.done(function (response) {
alert(response);
resetPUplButtons();
//close modal...
$('#profimgwin').modal('hide');
})
.fail(function (jqXHR, textStatus, error) {
alert('error sending file...' + error);
resetPUplButtons();
});
/////////////////////////end of ajax calls..
}else{
alert('you havent selected an image yet..');
resetPUplButtons();
}
});
and on my Laravel usercontroller I have this method that tries to upload the image but it's refusing to work.
public function setProfilePix(Request $request){
$file = $request->file('pimgupl');
$code = Auth::user()->profile->usrcode;
$targetDir = public_path() . DS . 'userdata'.DS.'ppix';
$newname = $targetDir.DS.strtolower($code).md5($code).'_'.time() .'.jpg';
// echo $newname;
//exit;
$file->move($targetDir, $newname);
echo 'saved';
}
I keep getting this error in my output panel:
Line 418 is the ajax operation, I have tried everything but nothing seems to be working. I have also added an exception to the route in my verifyCsrfToken.php - middleware, but still it isn't working.
In your jQuery try changing settings from
var settings = {
type: "POST",
url: "/user/setprofilepix",
data: fd
};
to
var settings = {
type: "POST",
url: "/user/setprofilepix",
data: fd,
processData: false,
contentType: false,
};

submit form data and files using phonegap?

I have created simple html form that contains text inputs, text area , files such as uploading images ..
how could I submit this form data when turning it into phone gap application that contains user registration to his data and photo and cv document?
when submitting data it should be sent to php page where mysql insert will held?
I have tried the serialize method face problems in getting data in th php page
also couldn't find the way to upload file and images??
any help???
<script>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("Hello ");
$("#button").click(function(evt){
var name = $("#name").val();
var message = $("#message").val();
var sendData = { "name": name, "message": message };
$.ajax({
type: "POST",
url: "http://localhost/webs/main/ajax/process.php",
data: sendData,
success: function(data) {
log.console(data);
$("#info").html(data);
}
});
alert("Hello ");
alert($("#test").val());
alert($("#name").val());
alert($("#message").val());
return false;
});
}
Upload image using phonegap
============================
function uploadImage(){
//Using Camera
navigator.camera.getPicture(uploadPhoto, onFailcapturePhoto, { quality: 50,destinationType: Camera.DestinationType.FILE_URI });
//Using library
navigator.camera.getPicture(uploadPhoto, onFailcapturePhoto, { quality: 50,destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
}
function onFailcapturePhoto(message) {
console.log("Message = " + message);
}
function uploadPhoto(imageURI) {
var imagefile = imageURI;
$('#vImage').attr('src', imagefile);
/* Image Upload Start */
var ft = new FileTransfer();
var options = new FileUploadOptions();
options.fileKey="vImage1";
options.fileName=imagefile.substr(imagefile.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
ft.upload(imagefile, your_service_url, win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
//alert($.parseJSON(r.response))
}
function fail(error) {
console.log("Response = " + error.code);
}
On your php file
=================
file_put_contents("file.txt", print_r($_FILES, true));
Post Form data and Image together
================================
// Here first submit your form input data after successfully submit upload image call
$('#submit').on('click', function(event){
if(event.handled !== true)
{
var ajax_call = serviceURL;
var str = $('#form').serialize();
$.ajax({
type: "POST",
url: ajax_call,
data: str,
dataType: "json",
success: function(response){
$.each(response, function(key, value) {
// after success submit data
if(response){
var imagefile = $('#vImage').attr('src');
/* Image Upload Start */
var ft = new FileTransfer();
var options = new FileUploadOptions();
options.fileKey="vImage1";
options.fileName=imagefile.substr(imagefile.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.mimeType="image/png";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
ft.upload(imagefile, your_service_url, win, fail, options);
}
});
}
});
event.handled = true;
}
return false;
})

How do you upload file(s) with AJAX

I am currently trying to upload a file through a form I made, using jQuery. This is what I am attempting to do:
function ajax_upload(){
var formData = new FormData($('form#userform'));
$.ajax({
url: location.protocol + "//" + location.host + "/profile/uploadPicture",
dataType: 'json',
data: formData,
type: 'post',
success: function(data, status){
if (data.status == 'error') {
$('#error').html(data.msg);
}
else {
var filename = location.protocol + "//" + location.host + "/data/profiles/" + data.msg;
$('input#filename').val(filename);
close_upload_form();
pop_profilechanger(filename);
}
}
});
return false;
}
the form appears to post to the backend, but while trying to return the filename from the uploaded file in a JSON object like:
echo json_encode(array('status' => $status, 'msg' => $msg));
Is there something wrong?
Please tell me
This is how I do it. If you want more information, rather than just my pasted code, check out this http://www.html5rocks.com/en/tutorials/file/dndfiles/ because my code was made for drag and drop files
handleFiles : function(files, evt, target)
{
console.log(target);
$.each(files, function(index, value)
{
var file = value;
reader = new FileReader();
reader.onload = function(evt)
{
var li = $("<li class='uploading'><img data-image-id='0' src='" + evt.target.result + "' /></li>");
target.find('.imagesList').append(li);
var request = new XMLHttpRequest();
var formData = new FormData();
formData.append('image', file);
request.open("Post", settings.uploadImageUrl);
request.addEventListener("load", function(evt)
{
var id = evt.target.responseText;
li.removeClass('uploading');
li.find('img').attr('data-image-id', id);
}, false);
request.send(formData);
};
reader.readAsDataURL(value);
});
},

Categories