qq_32929101
2017-11-29 08:23
采纳率: 80%
浏览 3.0k
已采纳

java代码实现pdf文档下载

楼主试了半天,想用controller直接实现来着,但一直都得不到文件

@Controller
@RequestMapping("/reportDownload")
public class ReportDownloadController extends BaseController{

private static Logger logger=Logger.getLogger(ReportDownloadController.class);

@RequestMapping("/downReport")
public HttpServletResponse busReport(HttpServletRequest request,BigDecimal modelId,BigDecimal planId,HttpServletResponse response) throws IOException {
    UtilReport util = new UtilReport();
    String fileDownloadName = null;
    String fileDisplayName = null;
    try {           
        IsReport isReport = util.initReport(modelId, planId,request);
        fileDownloadName = isReport.getRptFileName();
        fileDisplayName = isReport.getRptName();

// fileDisplayName = URLEncoder.encode(fileDisplayName, "UTF-8");
fileDisplayName = new String(fileDisplayName.getBytes("UTF-8"),"ISO-8859-1");
} catch (Exception e) {
System.out.println("报告不存在");
e.printStackTrace();
}
OutputStream outp = null;
BufferedInputStream bins = null;
FileInputStream in = null;
BufferedOutputStream bous = null;
try {

in = new FileInputStream(new File(fileDownloadName));
bins = new BufferedInputStream(in);

byte[] b = new byte[bins.available()];
bins.read(b);
bins.close();
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + fileDisplayName);
response.addHeader("Content-Length", "" + new File(fileDownloadName).length());
outp = response.getOutputStream();
bous = new BufferedOutputStream(outp);
response.setContentType("application/octet-stream");
bous.write(b);
bous.flush();
bous.close();
} catch (Exception e) {
System.out.println("文件下载失败!");
e.printStackTrace();
} finally {
if (in != null) {
in.close();
in = null;
}
if (outp != null) {
outp.close();
outp = null;
}
if (bins != null) {
bins.close();
bins = null;
}
if (bous != null) {
bous.close();
bous = null;
}
}

    return response;
}
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

6条回答 默认 最新

  • zxgmdzz 2017-11-29 08:39
    已采纳
    已采纳该答案
    打赏 评论
  • qq_32929101 2017-11-29 08:31

    图片说明

    打赏 评论
  • wusongqiong 2017-11-29 08:31

    和下载word文档的类似!若需要请私信!

    打赏 评论
  • 黄河默默 2017-11-29 08:50

    和普通的下载是一样的,设置好你的filename io流啥的都一样的 看你用的是springmMVC 查查他的下载就行了

    打赏 评论
  • qq_21689813 2017-11-29 08:59

    和下载普通的文件一样,设置好你要下载的文件的输出流等信息就可以!

    打赏 评论
  • 小马草上飞 2017-11-29 09:30

    跟下载普通文件一样的

    打赏 评论

相关推荐 更多相似问题