public class QRCodeServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String qrtext = request.getParameter("qrtext");
ByteArrayOutputStream out = QRCode.from(qrtext).to(ImageType.PNG).stream();
response.setContentType("image/png");
response.setContentLength(out.size());
OutputStream outStream = response.getOutputStream();
outStream.write(out.toByteArray());
outStream.flush();
outStream.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
这是我用于生成QRCode的代码。我使用outputStream将QRCode显示给浏览器。但是如何将QRCode保存为服务器上的图像文件并使用标签将其显示在另一个html文件中呢? 我在这里用iText lib生成QrCode。
答案 0 :(得分:1)
如果save是可选的,但是HTML文件中需要显示(实际上是JSP)...下一步呢?
如果请求中有参数txt
:
<% var txt = request.getParameter("txt"); %>
<img src="/context/servletMapping?qrtext=<%=java.net.URLEncoder(txt, "UTF-8")%>">
使用JSTL,请参阅How to URL-encode a String with JSTL?
答案 1 :(得分:0)
只需使用FileOutputStream将ByteArrayOutputStream的内容写入。将该内容写入响应输出流的方式相同。将文件写入通过HTTP可用的某个位置(例如,apache安装的文档根目录等),您可以从HTML中引用它。
您可以尝试的另一种方法是将图像直接内嵌到HTML代码中(新浏览器通过数据URI支持此功能)
答案 2 :(得分:0)
保存ByteArrayOutputStream
String imageDir = //directory to save
String fileName = //file name
ByteArrayOutputStream out = //image byte arary
File file = new File(imageDir, fileName);
OutputStream outStream = new FileOutputStream(newFile);
outStream.write(out.toByteArray());
outStream.close();