hikamen
2/25/2018 - 10:39 AM

文件下载或者查看

//下载文件
@RequestMapping(value = "/download/attachment/{id}", method = RequestMethod.GET)
    public void downloadAttachment(HttpServletResponse response,@PathVariable int id){
         try { 
                if(id > 0) {
                    Attachment attachment = this.attachmentService.load(id);
                    response.setContentType(attachment.getType());
                    response.setHeader("Content-disposition", "attachment; filename=\""+attachment.getName()+"\"");
                    FileCopyUtils.copy(attachment.getContent(), response.getOutputStream());
                }
         }catch (IOException e) {
                e.printStackTrace();
         }
    }


//在浏览器中查看
@RequestMapping("/view/{id}")
    public void view(@PathVariable("id") int id, HttpSession session, HttpServletResponse res){
        StdDoc stdDoc = this.stdDocService.load(id);
        if(StringUtils.endsWithIgnoreCase(stdDoc.getDocPath(), ".pdf")) {
            res.setContentType("application/pdf;charset=utf-8");
        }else {
            res.setContentType("application/msword;charset=utf-8");
        }
        FileInputStream in = null;
        try {
            res.setHeader("Content-Disposition", "inline; filename="+new String(stdDoc.getDocPath().getBytes("gb2312"),"iso8859-1"));
            in = new FileInputStream(new File(getBasePath(session) + stdDoc.getDocPath()));
            IOUtils.copy(in, res.getOutputStream());
              
        }catch(IOException e) {
            e.printStackTrace();
        }finally {
            if(in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }