将照片从javascript发送到服务器

时间:2012-12-24 07:16:27

标签: javascript ajax http servlets

伙计我是编程新手,我真的不知道如何将div中显示的照片保存到服务器。我正在使用java应用程序,我试图在div上显示图像,然后将其保存在服务器上。据我所知,由于客户端和服务器的兼容性,无法在jsp或servlet中声明javascript变量。我试图通过ajax传递url,但由于base64长字符串,它没有显示在服务器上。我想我们不能将这么长的字符串传递给jsp或servlet页面。有没有其他方法可以传递字符串或将图像保存到服务器?

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 个答案:

答案 0 :(得分:7)

创建一个类似的输入元素,

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

然后在ajax中,

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

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

如果要保存画布图,那么

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