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

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

1.效果图

这里写图片描述

在文本框里输入对应的文本,然后点击Dodnload按钮,会弹出下载框:
这里写图片描述

点击保存,然后打开如下图所示:
这里写图片描述

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()">Download</button>

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());
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值