Laravel upload image from Javascript given an image URL - javascript

I have an image URL in javascript extracted from a canvas in html and i want to create an image from that URL and upload it to my storage files in server.
i can send the Url in a ajax post request to my sendImagetoController function in controller or if there is a method from javascript to do that.My routes are all defined and tested.Please Help
my display.blade.php .
<html>
<head>
<title>HeatMap Display</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src='http://www.patrick-wied.at/static/heatmapjs/assets/js/heatmap.min.js'></script>
<script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script>
<script src="{{ asset('js/jquery.js')}}" type="text/javascript"></script>
<script src="{{ asset('js/app.js') }}" defer></script>
<script src="{{ asset('js/heatmap.js' )}}" type="text/javascript"></script>
<script>
var coordinatesarray = #json($coordinates);
var finalcoordinatesarr=[];
var count=0;
var mapId={{$targetHeatMap->id}};
var mintime=10000000;
var maxtime=0;
var imgUrl="";
coordinatesarray.forEach(element => {
var cor={
'x' : coordinatesarray[count]['x'],
'y' : coordinatesarray[count]['y'],
'value' : coordinatesarray[count]['time_spent']
};
if(mintime>coordinatesarray[count]['time_spent']){
mintime=coordinatesarray[count]['time_spent'];}
if(maxtime<coordinatesarray[count]['time_spent'])
maxtime=coordinatesarray[count]['time_spent'];
finalcoordinatesarr.push(cor);
count++;
});
console.log(finalcoordinatesarr);
function load(){
renderCanvas();
}
function renderCanvas(){
var heatmapInstance = h337.create({
container: document.getElementById('heatMap')
});
var testData = {
min: mintime,
max: maxtime,
data:finalcoordinatesarr
};
heatmapInstance.setData(testData);
imgUrl = (document.getElementById("heatMap").childNodes[0]).toDataURL();
document.getElementById("heatMapPic").src=imgUrl;
}
sendImageToController();
function sendImageToController(){
formdata = new FormData();
if($('#heatMapPic').prop('files').length>0){
file = $('#heatMapPic').prop('files');
formdata.append("heatMapPic",file);
}
formdata.append('tagetHeatMap',$('#targetHeatMap').val());
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name="csrf-token"]').attr('content') }
});
$.ajax({
url: "{{route('HeatMap.moveToStorage')}}",
data: formdata,
type:'post',
// traditional:true,
success:function(response){
console.log("correct");
console.log(response);
},
error:function(e){
console.log("errrooooor");
console.log(e);
},
});
console.log("hi");
}
</script>
</head>
<body onload="load()">
<form id="form" enctype="multipart/form-data">
#csrf
<input type="file" id="heatMapPic" name="heatMapPic" src=""/>
<input type="text" id="targetHeatMap" value="{{$targetHeatMap}}"/>
</form>
<div id="heatMap" style="height:740px"></div>
<a-scene>
{{-- <a-sky radius=10 opacity="0.8" src="{{asset('uploads/heat_map_images/'.$targetHeatMap->heatmap_image)}}"></a-sky> --}}
{{-- <a-sky radius=10 src="{{asset('uploads/'.$imageName)}}"></a-sky> --}}
</a-scene>
</body>
</html>
my Controller method
public function moveToStorage(Request $request){
return 'hello';
}

I use this method in PHP, the fact that the file itself comes to php through the variable $_FILES() and is not visible in the main query.
<?php
putenv("upload_tmp_dir=/var/www/site.com/public_html/upload/");
$uploadDir = getenv("upload_tmp_dir");
$uploadFile = $uploadDir . basename($_FILES['userfile']['name']);
move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadFile);
?>
Then you can open the file in the path in the $uploadFile variable

If you have url which is publicly accessible then you can use it like this
public function moveToStorage(Request $request){
$data = $request->all();
$url = $data['file_url'] ; //file url that you have in javascript
$contents = file_get_contents($url);
$name = substr($url, strrpos($url, '/') + 1);
Storage::put($name, $contents);
return 'hello';
}
OR if your file is posted as base64 then try this
public function moveToStorage(Request $request){
$data = $request->all();
$file = $data['file_url']; //base64 encoded image
$file = substr($file, strpos($file, ",")+1);
$imgeData = base64_decode($file);
$contents = file_get_contents($imgeData);
Storage::put("test.png", $contents);
return 'hello';
}

Looking at your code, it looks like you're trying to send the image before it is actually rendered. You need to move sendImageToController() inside your load function, after renderCanvas().
Also, no need for all the formData stuff. Just send the result of .toDataURL() as-is to the server, then use base64_decode() to turn it back into an image.
Here are the relevant changes:
function load() {
renderCanvas();
sendImageToController(); // send to server AFTER rendering
}
var imgUrl;
function renderCanvas() {
// ...
imgUrl = (document.getElementById("heatMap").childNodes[0]).toDataURL();
// ...
}
Shorter AJAX code:
function sendImageToController() {
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
$.post("{{route('HeatMap.moveToStorage')}}", {
heatmap: imgUrl // global var set in renderCanvas()!!
})
.done(function(response) {
console.log("correct");
console.log(response);
})
.fail(function(e) {
console.log("errrooooor");
console.log(e);
});
}
On the server, grab the heatmap parameter.
public function moveToStorage(Request $request){
$heatmap = $request->input('heatmap');
$base64 = explode(",", $heatmap)[1];
$binary = base64_decode($base64);
// store $binary data in PNG file
return 'image saved successfully';
}

Related

How should I access a variable from javascript in PHP to perform some actions?

I have a file named sample.php, in which I have some JS code, and some PHP code. This is some sort of sample snippet of the code I have :
<!DOCTYPE html>
<html lang="en">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<head>
<script type="text/javascript">
var ThunkableWebviewerExtension = {
receiveMessage: function(fxn) {
var callbackFunction = function(event) {
if (typeof fxn === 'function') {
fxn(event.data)
}
};
document.addEventListener('message', callbackFunction, false);
window.addEventListener('message', callbackFunction, false);
}
}
</script>
</head>
<body>
<script type="text/javascript">
var value;
ThunkableWebviewerExtension.receiveMessage(function(message) {
value = message;
});
//sending the value with ajax
$.ajax({
url : "./sample.php", //same file
method : "GET",
data: {"name": value},
success : (res) => {
console.log(value);
},
error : (res) => {
console.log(res);
}
})
</script>
<?php
echo $_GET['name'];
?>
</body>
</html>
The problem is the PHP code doesn't print anything - Are there any error/bug I need to fix? Or is there a better method for accessing a JS variable in PHP?
Thanks! :)
Here's how you can access PHP code within in a <script> (without using AJAX):
<?php
echo"<script>";
include ('javascriptStuff.js');
echo'let x = '.json_encode($phpVariable).';';
echo"</script>";
?>

Send QR result to codebehind method with function

I'm using as reference this code https://www.itsolutionstuff.com/post/jquery-html5-qr-code-scanner-using-instascan-js-exampleexample.html when i get the result of the QR y send it to a variable, what I try to do and I don't get a result is that when I want to send a function in the codebehing I never get a response result.
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script src="../Scripts/jquery-3.3.1.min.js"></script>
<script src="assets/js/instascan.min.js"></script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<video id="preview" class="col-lg-12"></video>
<script type="text/javascript">
let scanner = new Instascan.Scanner({ video: document.getElementById('preview') });
scanner.addListener('scan', function (content) {
var test = content.toString(); //here i get the variable
alert(test);
<%=SendToDB(content)%>;
});
Instascan.Camera.getCameras().then(function (cameras) {
if (cameras.length > 0) {
scanner.start(cameras[0]);
} else {
console.error('There is no camera');
}
}).catch(function (e) {
console.error(e);
});
</script>
</div>
</div>
</div>
</asp:Content>
Now in codebehind I have something like this
public void SendToDB(string content)
{
string variable = content;
//here I send it to the database
}
I know this is an older question but I was struggling with this too so I wanted to post an answer for anyone else. Try changing your html code to this:
<script type="text/javascript">
let scanner = new Instascan.Scanner({ video: document.getElementById('preview') });
scanner.addListener('scan', function (content) {
var test = content.toString(); //here i get the variable
alert(test);
var options = {};
options.url = "Default.aspx/SendToDB";
options.type = "POST";
options.data = JSON.stringify({ content });
options.dataType = "json";
options.contentType = "application/json";
options.success = function (result) { };
options.error = function (err) { };
$.ajax(options);
});
Instascan.Camera.getCameras().then(function (cameras) {
if (cameras.length > 0) {
scanner.start(cameras[0]);
} else {
console.error('There is no camera');
}
}).catch(function (e) {
console.error(e);
});
</script>
What is important here is the "options.url = "Default.aspx/SendToDB";". If the name of your page isn't Default.aspx then you need to change it to the correct page name.
Now in your C# code you need to add [WebMethod] above your function:
[WebMethod]
public void SendToDB(string content)
{
string variable = content;
//here I send it to the database
}

How to pass post results from one html to other html?

I want to pass results (return value of POST) from one page into other embedded page, and I don't know how can I do it.
The structures look like:
main html page (Welcome.html) which has ej2 file (Buttom.html):
Welcome.html:
<html>
<body>
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
xhr.open("POST", "/addGrade", true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
data = // logic to get the data (i skipped adding this part)
xhr.send(data);
xhr.onloadend = function () {
// HERE I WANT TO PASS THE RESULTS TO Buttom.html
};
}); // click on submit
}); // ready
</script>
<form id="gradeForm">
<p>
<label>Name:</label>
<input type="text" name="name" id="name">
</p>
<p>
<label>Grade:</label>
<input type="text" name="grade" id="grade" value="100">
</p>
<p>
<button type="button" id="submit" >submit</button>
</p>
</form>
<div>
<%include Buttom.html%>
</div>
</body>
</html>
Buttom.html:
<head>
</head>
<body>
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
}); // ready
</script>
<p id="ppp">
<!-- Here I want to add the results -->
<p>
</body>
How can I pass the results from POST (in welcome.html) to Buttom.html (i.e into function of js in Buttom.html) ?
Welcome.HTML
$(document).ready(function(){
$("#submit").click(function(){
xhr.open("POST", "/addGrade", true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
data = // logic to get the data (i skipped adding this part)
xhr.send(data);
xhr.onloadend = function () {
// If your data is big then use cookies or create form and send it to another page
var url = "YourPage?data=" + encodeURIComponent(YOUR_DATA);
window.location.href = url;
};
}); // click on submit
}); // ready
ON Buttom.html:
$(document).ready(function(){
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (window.location.search.split('?').length > 1) {
var params = window.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["name"] != null) {
// YOUR CODE
}
});
});

PHP: Export a JSON file and catch it by JS

Got a php code:
<?php
$date = date("Y/m/d");
echo json_encode($date);
?>
It exports a json file. But then, I wanna catch it by JS:
$.get("/your/url").done(function(data){
});
But my problem is - how can I know where the JSON file was saved (if it even was saved)?
Does the echo json_encode($date) exports a json file to somewhere? Or echo has nothing to do with that?
Thanks for any further help.
Edit: Anybody can help me?
Your are doing correctly in php side but in jquery side i dont know if $.get().done() works or not
i have used it by this way and its working fine
$.getJSON( "url/yoururl", function( data ) {
console.log(data);
});
You can also use
$.ajax({
method:GET,
url:'url/yoururl',
success:function(data){
console.log(data);
}
});
console.log(data) will return date which you have exported from php
I don't jQuery, but the concept is identical.
001-tmp.php
<?php
$date = date("Y/m/d");
echo json_encode($date);
?>
001-tmp.html
<!doctype html>
<html>
<head>
<script>
"use strict";
function byId(id){return document.getElementById(id)}
function ajaxGet(url, onLoad, onError)
{
var ajax = new XMLHttpRequest();
ajax.onload = function(){onLoad(this);}
ajax.onerror = function(){console.log("ajax request failed to: "+url);onError(this);}
ajax.open("GET",url,true);
ajax.send();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
byId('goBtn').addEventListener('click', onBtnClick, false);
}
function onBtnClick(evt)
{
ajaxGet('001-tmp.php', onLoad, onError);
function onLoad(ajax)
{
var rawData = ajax.responseText;
var parsedData = JSON.parse(rawData);
byId('ajaxTarget').innerHTML = parsedData;
}
function onError(ajax)
{
// todo: add something useful here
}
}
</script>
<style>
</style>
</head>
<body>
<button id='goBtn'>Get data from PHP</button>
<div id='ajaxTarget'></div>
</body>
</html>

How to send static html as an email content in c#?

I am sending an static html with some dynamic content to user email id using c# and JQuery.
Below is the JavaScriot file from where I am calling th method SendEmail.
$(".EmailInvoice").click(function () {
$.ajax({
type: 'POST',
url: siteUrl + '/invoiceEmail.asmx/SendEmail',
data: JSON.stringify({ }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
},
failure: function (data) {
},
error: function () {
alert("error");
}
});
Below is the invoiceEmail.asmx file
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Web.Services;
using System.Web.Hosting;
namespace meltwish
{
/// <summary>
/// Summary description for invoiceEmail
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class invoiceEmail : System.Web.Services.WebService
{
public static string PopulateBody(string userName, string title, string url, string description)
{
string body = string.Empty;
using (StreamReader reader = new StreamReader(HostingEnvironment.MapPath("~/EmailTemplate.html")))
{
body = reader.ReadToEnd();
}
body = body.Replace("{UserName}", userName);
body = body.Replace("{Title}", title);
body = body.Replace("{Url}", url);
body = body.Replace("{Description}", description);
return body;
}
public static void SendHtmlFormattedEmail(string recepientEmail, string subject, string body)
{
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["username"]);
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
mailMessage.To.Add(new MailAddress(recepientEmail));
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["Host"];
smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
smtp.Send(mailMessage);
}
//object sender, EventArgs e
[WebMethod]
public static string SendEmail()
{
//string body = this.PopulateBody("John",
string body = PopulateBody("John",
"Fetch multiple values as Key Value pair in ASP.Net AJAX AutoCompleteExtender",
"http://www.aspsnippets.com/Articles/Fetch-multiple-values-as-Key-Value-pair-" +
"in-ASP.Net-AJAX-AutoCompleteExtender.aspx",
"Here Mudassar Ahmed Khan has explained how to fetch multiple column values i.e." +
" ID and Text values in the ASP.Net AJAX Control Toolkit AutocompleteExtender"
+ "and also how to fetch the select text and value server side on postback");
SendHtmlFormattedEmail("wajedkh#gmail.com", "New article published!", body);
//this.SendHtmlFormattedEmail("wajedkh#gmail.com", "New article published!", body);
return "sajjad";
}
}
}
This is the HTMl file that is added to the project. The name is EmailTemplate.html
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<!-- Server CDN Files -- Start -->
<!--<link class="temp" href="http://klcdn.meltwish.com/styles/store/1.0.2/store.css" rel="stylesheet" />-->
<link href="http://localhost:60339/styles/store/1.0.2/store.css" rel="stylesheet" />
</head>
<body>
<img src = "http://www.aspsnippets.com/images/Blue/Logo.png" /><br /><br />
<div style = "border-top:3px solid #22BCE5"> </div>
<span style = "font-family:Arial;font-size:10pt">
Hello <b>{UserName}</b>,<br /><br />
A new article has been published on ASPSnippets.<br /><br />
<a style = "color:#22BCE5" href = "{Url}">{Title}</a><br />
{Description}
<br /><br />
Thanks<br />
ASPSnippets
</span>
</body>
</html>
This i have added in the Web.Config file.
<appSettings>
<add key="Host" value="smtp.gmail.com"/>
<add key="EnableSsl" value="true"/>
<add key="UserName" value="hussainsajjad9991#gmail.com"/>
<add key="Password" value="xxxxx"/>
<add key="Port" value="587"/>
</appSettings>
Actually whenever I have trying to call the javascript ajax method it is going to the error content.
Help me....
Following C# Code Work For me
[System.Web.Services.WebMethod]
public static string SendEmail()
{
using (MailMessage mm = new MailMessage("From", "To"))
{
mm.Subject = "Subject ";
mm.Body = "<html><head></head><body> Content</body></html>";
mm.IsBodyHtml=true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = false;
NetworkCredential NetworkCred = new NetworkCredential("From", "password");
smtp.UseDefaultCredentials = false;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Timeout = 2000000;
smtp.Send(mm);
return "Success";
}
}
And Use Ajax Code
$.ajax({
type: "POST",
url: siteUrl + '/invoiceEmail.aspx/SendEmail',
data: "{}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (t) { alert(t); },
error: function (t) { alert(t); } })

Categories

Resources