2013-07-02 154 views
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> 
} 

這裏是我用於生成QRCode的代碼。我用outputStream來顯示QRCode到瀏覽器。但是,如何將QRCode另存爲服務器上的圖像文件並使用標籤將其展示在另一個html文件中? 我使用iText庫在這裏生成QrCode。如何保存我剛剛生成的QRCode圖像文件到服務器?

回答

1

如果圖像保存是可選的,但在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?

0

只需使用FileOutputStream將ByteArrayOutputStream的內容寫入即可。與將內容寫入響應輸出流的方式相同。將文件寫入某個可通過HTTP訪問的位置(例如,apache安裝的文檔根目錄等),然後您可以從HTML中引用它。

另一種方法,你可以嘗試將直接內嵌圖像到您的HTML代碼(全新的瀏覽器通過數據URI支持這個)

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(); 
相關問題