我一直在嘗試從我的HTML頁面中將畫布圖像保存到Java Servlet中的圖像文件。我需要通過Ajax請求將圖像從HTML發送到Java Servlet。有人可以幫我嗎?我已經嘗試了以下選項從Java Servlet將畫布圖像保存爲png圖像文件
這裏,request.getPart("myImg")
是返回null,因此,這是行不通的。請幫助我。
我也曾嘗試以下解決方案 Sending content of canvas to java
這裏的問題是,它給我的無效文字/長度異常在下面的行設置
BufferedImage bfi = ImageIO.read(new ByteArrayInputStream(decodedBytes));
請幫幫忙! !
UPDATE:
這是我的Ajax代碼:
function uploadImage() {
var canvasServer = document.getElementById("canvasThumbResult");
var context = canvasServer.getContext("2d");
var imageDataURL = canvasServer.toDataURL('image/png');
var xhr = new XMLHttpRequest();
xhr.open("POST", trinityCvaServicesUrl+"common/uploadImage", true);
var boundary = Math.random().toString().substr(2);
xhr.setRequestHeader("content-type",
"multipart/form-data; charset=utf-8; boundary=" + boundary);
var multipart = "--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=myImg\r\n" +
"Content-type: image/png\r\n\r\n" +
imageDataURL + "\r\n" +
"--" + boundary + "--\r\n";
xhr.send(multipart);
/*xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("imgData="+imageDataURL);*/
}
這裏是我的Java代碼:
FileOutputStream fos = null;
try {
Part part = req.getPart("myImg");
BufferedReader br = new BufferedReader(new InputStreamReader(
part.getInputStream(), Charset.forName("utf-8")));
/*String imgData = request.getParameter("imgData");
BufferedReader br = new BufferedReader(new InputStreamReader(
new ByteArrayInputStream(
imgData.getBytes(StandardCharsets.UTF_8)),
Charset.forName("utf-8")));*/
String sImg = br.readLine();
sImg = sImg.substring("data:image/png;base64,".length());
byte[] bImg64 = sImg.getBytes();
byte[] bImg = Base64.decodeBase64(bImg64);
fos = new FileOutputStream(ReloadableProps.getProperty("local.image.save.path")+"img.png");
fos.write(bImg);
/*String imgData = req.getParameter("imgData");
String img64 = imgData.replaceAll("data:image/png;base64,", "");
byte[] decodedBytes = DatatypeConverter.parseBase64Binary(img64);
BufferedImage bfi = ImageIO.read(new ByteArrayInputStream(decodedBytes));
File outputfile = new File(ReloadableProps.getProperty("local.image.save.path")+"img.png");
ImageIO.write(bfi , "png", outputfile);
bfi.flush();*/
} catch (Exception e) {
e.printStackTrace();
String loggerMessage = "Upload image failed : ";
CVAException.printException(loggerMessage + e.getMessage());
} finally {
if(fos != null) {
fos.close();
}
}
而是鏈接到不同的問題,希望我們可以猜測你如何修補起來他們的代碼,爲什麼不發表您的Ajax代碼? – developerwjk
感謝您的回覆。我在我的問題中發佈了ajax和java代碼。請幫助.. – ArinCool
您也應該發佈堆棧跟蹤,並指出堆棧跟蹤的頂部在源代碼中與哪條線對應。或者以其他方式指示上述方式無效。 – haraldK