使用DWR3.0进行文件的下载

这里主要讲解下如何通过DWR3.0进行文件的下载。

1.效果图

这里写图片描述

在文本框里输入对应的文本,然后点击Dodnload按钮,会弹出下载框:
使用DWR3.0进行文件的下载_第1张图片

点击保存,然后打开如下图所示:
使用DWR3.0进行文件的下载_第2张图片

2.原理

客户端代码获取输入框值,并传递到后台Java中的UploadDownload.downloadPdfFile()方法,当服务器段代码给我们返回一个PDF文件的时候,我们打开下载窗口:

function downloadPdfFile() {
  var pdftext = dwr.util.getValue('pdftext');

  UploadDownload.downloadPdfFile(pdftext, function(data) {
    dwr.engine.openInDownload(data);
  });
}

服务器端函数通过使用iText 来生成一个PDF文件,然后以一个FileTransfer 对象的形式返回给客户端:

ByteArrayOutputStream buffer = new ByteArrayOutputStream();

Document document = new Document();
PdfWriter.getInstance(document, buffer);

document.addCreator("DWR.war using iText");
document.open();
document.add(new Paragraph(contents));
document.close();

return new FileTransfer("example.pdf", "application/pdf", buffer.toByteArray());

3.源码

3.1HTML source:

<input type="text" id="pdftext" value="Hello, World" size="20"/>
<button onclick="downloadPdfFile()">Downloadbutton>

3.2Javascript source:

function downloadPdfFile() {
  var pdftext = dwr.util.getValue('pdftext');

  UploadDownload.downloadPdfFile(pdftext, function(data) {
    dwr.engine.openInDownload(data);
  });
}

3.3Java source:

public FileTransfer downloadPdfFile(String contents) throws Exception {
    if (contents == null || contents.length() == 0) {
        contents = "[BLANK]";
    }

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, buffer);

    document.addCreator("DWR.war using iText");
    document.open();
    document.add(new Paragraph(contents));
    document.close();

    return new FileTransfer("example.pdf", "application/pdf", buffer.toByteArray());
}

你可能感兴趣的:(DWR)