SSM上传PDF并预览
1、两种方式:一种传到项目下,直接预览;另一种传到专门的存储位置,通过设置虚拟路径预览。
2、1.上传到项目下并预览。控制器:@RequestMapping(value = "/uploadPDF&qu泠贾高框ot;, method = RequestMethod.POST) @ResponseBody public Map<String, Object> UploadPDF(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) { Map<String, Object> map = new HashMap<String, Object>(); String sno = "123456"; // (String)request.getSession().getAttribute("username"); // 获得原始文件名 String fileName = file.getOriginalFilename(); System.out.println("原始文件名:" + fileName); // 新文件名 String newFileName = sno + "docPDF.pdf"; // 获得项目的路径 ServletContext sc = request.getSession().getServletContext(); // 上传位置 String path = sc.getRealPath("/uploadPDF") + "/"; // 设定文件保存的目录 File f = new File(path); if (!f.exists()) f.mkdirs(); if (!file.isEmpty()) { try { FileOutputStream fos = new FileOutputStream(path + newFileName); InputStream in = file.getInputStream(); int b = 0; while ((b = in.read()) != -1) { fos.write(b); } fos.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } } System.out.println("上传pdf到:" + path + newFileName); map = JsonModelUtil.JsonModel("1", "文件提交成功", 1, null); return map; }
3、上传jsp:<form action="path/uploadPDF1" method="post" enctype="multipart/form-data">协议书:<input type="file" class="form-horizontal" name="file" /> <input type="submit" value="上 传" /></form>
4、预览jsp:<iframe width=100% height=800 scrolling='no' frameborder='0' src='/GraduationProject/uploadPDF/${param.sno }docPDF.pdf' ></iframe>
5、如果是传到项目下边可以直接预览,不用做其他设置,优点是方便简单,缺点是如果需要上传的文件过多,会造成项目体积过大,对文件过多的情况不适用。所以可以考虑放在专门的存储位置,然后通过虚拟路径预览。