问题描述
我从网页发送一张描绘在canvas图片给后台,直接用JavaScript的.toDataURL("image/png")的BASE64编码发到后台接收,解码成byte[]然后保存成PNG图片,但图片一遍黑,还有后台保存的黑图片明显比我在网页另存为少几K我测过是BASE64数据,而且后台的跟前台一模一样,没看出有什么错代码贴上:packagecn.create.servlet;importjava.io.File;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.apache.commons.codec.binary.Base64;@WebServlet("/AcceptFileServlet")publicclassAcceptFileServletextendsHttpServlet{privatestaticfinallongserialVersionUID=1L;publicAcceptFileServlet(){super();}protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doPost(request,response);}protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{request.setCharacterEncoding("UTF-8");response.setCharacterEncoding("UTF-8");Stringpath=request.getSession().getServletContext().getRealPath("/images/");//路径StringimageData=request.getParameter("imageData");byte[]imageByte=decodeBase64(imageData);saveFile(imageByte,path);System.out.print(imageData);}publicbyte[]decodeBase64(StringimageData){byte[]imageByte=null;//删除标记intdou=imageData.indexOf(",");imageData=imageData.substring(dou+1);booleanyes=Base64.isBase64(imageData);imageByte=Base64.decodeBase64(imageData);for(inti=0;i<imageByte.length;++i){if(imageByte[i]<0){//调整异常数据imageByte[i]+=256;}}returnimageByte;}publicvoidsaveFile(byte[]imageByte,Stringpath){Filefile=newFile(path+"/test.png");FileOutputStreamoutStream=null;try{outStream=newFileOutputStream(file);outStream.write(imageByte);}catch(FileNotFoundExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}finally{try{outStream.flush();outStream.close();}catch(IOExceptione){e.printStackTrace();}}}}
解决方案
解决方案二:
找到问题了,是因为url传值到后台的时候,接受的数据会把+号变成空格,问题解决是就是把空格替换还原为+号。哎,没人答!