0
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>
}

Here is the code I use for generating QRCode. I used outputStream to display the QRCode to browser. But how can I save that QRCode as an image file on server and use tag to dislay it in another html file? I used the iText lib to generate QrCode here.

fmodos
  • 4,472
  • 1
  • 16
  • 17

3 Answers3

1

If save is optional, but display is needed in the HTML file (actually a JSP)... What about the next?

If there is a parameter txt in the request:

<% var txt = request.getParameter("txt"); %>
<img src="/context/servletMapping?qrtext=<%=java.net.URLEncoder(txt, "UTF-8")%>">

With JSTL, see How to URL-encode a String with JSTL?

Community
  • 1
  • 1
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
0

Just use a FileOutputStream to write the content of your ByteArrayOutputStream to. The same way you wrote that content to the response output stream. Write the file to some location available via HTTP (e.g. the document root of an apache installation, etc.) and you can refer to it from HTML.

Another approach you could try would be to inline the image directly into your HTML code (new browsers support this via data URIs)

0

Code example to save an image of a 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();
fmodos
  • 4,472
  • 1
  • 16
  • 17