Sending photo from javascript to server

2019-03-07 07:38发布

问题:

Guys i am new to programming and i am really not aware of how to save a photo which is displayed in a div to server. I am working with java application and i am trying to display an image on div and then later save it on the server. As i know javascript variables cannot be declared in jsp or servlets because of client and server compatibility. I am trying to pass the url through ajax but its not getting displayed on the server because of base64 long string. I think we cannot pass such long string to jsp or servlet pages. Is there any alternate way i can pass the string or save image to the 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);
}

回答1:

Create an input element like that,

 <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 are saving canvas drawing then,

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 );
}
?>