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

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
    关注
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 软件定义网络mininet和onos控制器问题
  • ¥15 微信小程序 用oss下载 aliyun-oss-sdk-6.18.0.min client报错
  • ¥15 ArcGIS批量裁剪
  • ¥15 labview程序设计
  • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
  • ¥15 Cloudreve保存用户组存储空间大小时报错
  • ¥15 伪标签为什么不能作为弱监督语义分割的结果?
  • ¥15 编一个判断一个区间范围内的数字的个位数的立方和是否等于其本身的程序在输入第1组数据后卡住了(语言-c语言)
  • ¥15 Mac版Fiddler Everywhere4.0.1提示强制更新
  • ¥15 android 集成sentry上报时报错。