java 文件下载
在此之前需要先简绍一下常见的MIME类型,以供之后使使用:
内容类型 | 文件扩展名 | 描述 |
---|---|---|
application/msword | doc | Microsoft Word |
application/octet-stream bin | dms lha lzh exe class | 可执行程序 |
application/pdf | Adobe Acrobat | |
application/postscrip | ai eps ps | PostScript |
appication/powerpoint | ppt | Microsoft Powerpoint |
appication/rtf | rtf | rtf 格式 |
appication/x-compress | z | unix 压缩文件 |
application/x-gzip | gz | gzip |
application/x-gtar | gtar | tar 文档 (gnu 格式 ) |
application/x-shockwave-flash | swf | MacroMedia Flash |
application/x-tar | tar | tar(4.3BSD) |
application/zip | zip | winzip |
audio/basic | au snd | sun/next 声音文件 |
audio/mpeg | mpeg mp2 | Mpeg 声音文件 |
audio/x-aiff | mid midi rmf | Midi 格式 |
audio/x-pn-realaudio | ram ra | Real Audio 声音 |
audio/x-pn-realaudio-plugin | rpm | Real Audio 插件 |
audio/x-wav | wav | Microsoft Windows 声音 |
image/cgm | cgm | 计算机图形元文件 |
image/gif | gif | COMPUSERVE GIF 图像 |
image/jpeg | jpeg jpg jpe | JPEG 图像 |
image/png | png | PNG 图像 |
下载代码实例:
public void downloadCamPlugIn(HttpServletResponse response) {
ServletOutputStream out = null;
InputStream inputStream = null;
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/octet-stream bin");
StringBuffer sheetName = new StringBuffer();
sheetName.append("摄像头插件.exe");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(sheetName.toString(), "utf-8"));
List<ArrayList<ExcelDataNode>> excelDataNodelist = new ArrayList<>();
ReadConfig readConfig = new ReadConfig();
inputStream = readConfig.getPlugIn();
out = response.getOutputStream();
int b = 0;
byte[] buffer = new byte[1024];
while ((b = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, b);
}
}catch (IOException e){
e.printStackTrace();
}finally {
try {
out.flush();
out.close();
inputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
关于setCharacterEncoding不做详述,此处最重要的是setContentType,此处的值是上面所描述的 mime类型,可以根据自己下载的文件类型选择对应的类型,setHeader设置下载完成后文件的名称