`

servlet 文件下载

 
阅读更多

File f = new File(filePath);  //path为文件路径
 BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;
        response.reset(); // 非常重要
        if (isOnLine==true) { // 在线打开方式
            URL u = new URL("file:///" + filePath);
//            response.setContentType(u.openConnection().getContentType());
//            response.setContentType("application/octet-stream");                    response.setContentType("text/plain");  *备注1   
response.addHeader("Content-Disposition", "inline; filename=" + f.getName());
          //inline是在线打开  
            // 文件名应该编码成UTF-8
        } else { // 纯下载方式
            response.setContentType("application/x-msdownload");  *备注1
           
            response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
        }
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0)
            out.write(buf, 0, len);
        br.close();
        out.close();
    }

 

response.setContentType 对应的文件类型
image/bmp--BMP

image/gif--GIF
image/jpeg--JPEG
image/tiff--TIFF
image/x-dcx--DCX

image/x-pcx--PCX
text/html--HTML
text/plain--TXT

text/xml--XML
application/afp--AFP
application/pdf--PDF
application/rtf--RTF
application/msword--MSWORD
application/vnd.ms-excel--MSEXCEL
application/vnd.ms-powerpoint--MSPOWERPOINT
application/wordperfect5.1--WORDPERFECT
application/vnd.lotus-wordpro--WORDPRO
application/vnd.visio--VISIO

application/vnd.framemaker--FRAMEMAKER
application/vnd.lotus-1-2-3--LOTUS123

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics