Uploading photos from javascript to server

Guys, I'm new to programming, and I really don't know how to save the photo that appears in the div on the server. I am working with a java application and I am trying to display an image on a div and then save it to the server. Since I know that javascript variables cannot be declared in jsp or servlets due to client and server compatibility. I am trying to pass url via ajax, but it does not appear on the server due to the long base64 string. I think we cannot pass such a long string to jsp or servlet pages. Is there an alternative way that I can pass a string or save an image on a server?

function GetXmlHttpObject() { var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { //Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } function ajax() { xmlHttp=GetXmlHttpObject(); var url="/ServletExten/XmlServletGen"; url=url+"?datax=" +cordXSend +"&datay=" +cordYSend +"&sizew=" +canvasWidth +"&sizeh=" +canvasHeight ; alert(url); xmlHttp.open("POST",url,true); xmlHttp.send(null); } 
-2
source share
1 answer

Create such an input element,

  <form id="fileupf" action="fileup.php" method="post" enctype="multipart/form-data"> <input type="file" id="fileup" name="file" accept="image/*" > </form> 

Then in ajax,

 $('#fileupf').ajaxForm({ complete: function(xhr) { alert("Upload complete"); } }); 

In php,

 <?php $target_path = "uploaded_images/"; $file_name = $_FILES["file"]["name"]; $random_digit=rand(0000,9999); $new_file_name=$random_digit.$file_name; $target_path = $target_path . basename( $new_file_name); ?> 

If you save a canvas drawing,

Javascript

 var canvasData = canvas.toDataURL("image/png"); var ajax = new XMLHttpRequest(); ajax.open("POST",'save.php',false); ajax.setRequestHeader('Content-Type', 'application/upload'); ajax.send(canvasData); 

Php

 <?php if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) { // Get the data $imageData=$GLOBALS['HTTP_RAW_POST_DATA']; $filteredData=substr($imageData, strpos($imageData, ",")+1); $unencodedData=base64_decode($filteredData); $random_digit=md5(uniqid(mt_rand(), true)); $fp = fopen( 'yourfolder/new'.$random_digit.'.png', 'wb' ); fwrite( $fp, $unencodedData); fclose( $fp ); } ?> 
+7
source

All Articles