自己的代码-(无法找到文件):
主要问题在于无法找到相应的文件,各位游客如果看到我的代码中有哪些问题请勇敢大声的指出来:
@RequestMapping("showAttachmentPDF")
public String showAttachmentPDF(Model model,HttpServletRequest req) {
HttpServletRequest request = TrustWebUtils.getRequest();
HttpServletResponse response = TrustWebUtils.getReponse();
String fileName = request.getParameter("fileName");
String path = request.getContextPath();
// etrading
String path1="/resources/doc/protocol.pdf";
path += path1;
response.setContentType("application/pdf");
FileInputStream in;
OutputStream out;
try {
in = new FileInputStream(new File(path));
out = response.getOutputStream();
byte[] b = new byte[1024 * 8];
while ((in.read(b)) != -1) {
out.write(b);
}
out.flush();
in.close();
out.close();
} catch (FileNotFoundException e) {
throw new BusinessException("",MessageUtils.getMessage("找不到文件"));
} catch (IOException e) {
throw new BusinessException(MessageUtils.getMessage(ErrorCodes.FILE_DOWN_EXCEPTION));
}
return null;
}
网上摘抄的代码-(亲测可用):
【出处】http://blog.youkuaiyun.com/fuyesunwang123/article/details/30241341
@RequestMapping("/act/worldcup_schedule_time/imgdownload")
@ResponseBody
public String scheduleDownload(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
response.setCharacterEncoding("UTF-8");
String downLoadName = "worldcup.jpg";
InputStream input = null;
try {
request.setCharacterEncoding("UTF-8");
//获取文件的路径
// String url = session.getServletContext().getRealPath("/") + "resources\\images\\act\\worldcup_merge\\worldcup720.png";
String url = session.getServletContext().getRealPath("/") + "resources/images/act/worldcup_merge/worldcup720.png";
System.out.println(url);
File file = new File(url);
input = FileUtils.openInputStream(file);
byte[] data = IOUtils.toByteArray(input);
//System.out.println("文件名:"+downLoadName);
response.reset();
//设置响应的报头信息(中文问题解决办法)
response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(downLoadName, "UTF-8"));
response.addHeader("Content-Length", "" + data.length);
response.setContentType("image/png; charset=UTF-8");
IOUtils.write(data, response.getOutputStream());
} catch (Exception e) {
logger.error("下载图片出错");
if (input != null) {
IOUtils.closeQuietly(input);
}
}
return null;
}