最近做HTML5拍照功能,要把客户端所拍照片上传到服务器并保存为图像。试过很多次,存的图像总是透明的,很是郁闷。把代码贴出来,请各位牛人指点一下。谢谢了!
/*前台传值代码*/
document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 640, 480);
var imgdata = canvas.toDataURL("image/jpg").substr(22);
var xmlRep;
if (window.XMLHttpRequest){
xmlRep=new XMLHttpRequest();
}
else{
xmlRep=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlRep.onreadystatechange=function(){
if (xmlRep.readyState==4 && xmlRep.status==200){
alert("保存成功");
}
}
xmlRep.open("post","SavePhoto.jsp",true);
xmlRep.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xmlRep.send("imgdata="+imgdata);
imgdata = null;
});
/*后台jsp页面,java代码*/
String imgdata = String.valueOf(request.getParameter("imgdata"));
if(imgdata==null)
return;
StringBufferInputStream strstream = new StringBufferInputStream(imgdata);
int size = strstream.available();
byte[] buffer = new byte[size];
strstream.read(buffer,0,size);
strstream.close();
String tmp = new String(buffer);
tmp = tmp.replaceAll("
","");
byte[] outData = org.apache.commons.codec.binary.Base64.decodeBase64(tmp);
OutputStream fos = new FileOutputStream("D:/aaa.png");
fos.write(outData,0,outData.length);
fos.close();
/*输出的aaa.png在美图看看中打开*/

------解决方案--------------------
大小不是 0 字节,看来已经写入了
估计是你的文件头没写好