标签:puts inpu name write http download while com try
实现效果如下:
代码为:
@RequestMapping(value = "/tools/printContract") public void cell(HttpServletResponse response,HttpServletRequest request,String outName) { //根据outName获取到保存在服务器上的文件 String filePath = request.getSession().getServletContext().getRealPath(ImgUtil.TOOLS_PATH+ImgUtil.TOOLS_TXT)+‘/‘+outName+".txt"; try(OutputStream out = response.getOutputStream()) { Date currentTime = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss"); String dateString = formatter.format(currentTime); //fileName是输出的文件的名字(不支持中文),包括了后缀 String fileName = "EncryptFile_" + dateString + ".txt"; byte[] bytes = FileEcodeUtil.file2byte(filePath); response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition","attachment;filename=" + fileName); response.setContentLength(bytes.length); out.write(bytes); out.flush(); } catch (IOException e) { //e.printStackTrace(); } } //上面用到的file2byte方法为: public static byte[] file2byte(String filePath) { byte[] buffer = null; File file = new File(filePath); try (FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream()) { byte[] b = new byte[1024]; int n; while ((n = fis.read(b)) != -1) { bos.write(b, 0, n); } buffer = bos.toByteArray(); } catch (Exception e) { // e.printStackTrace(); } return buffer; }
原创文章,欢迎转载,转载请注明出处!
标签:puts inpu name write http download while com try
原文地址:http://www.cnblogs.com/acm-bingzi/p/springPrintFile.html