java接口返回文件流:预览,下载
@GetMapping("/download/{filename}")
public void test(@PathVariable("filename") String filename, HttpServletResponse response) {
//文件路径
String filepath = "";
try {
File file = new File(filepath + filename);
FileInputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
//响应文件格式
response.setContentType(this.getContentType(this.getSuffix(filename)));
response.setContentLengthLong(file.length());
int len = 0;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes)) != -1) {
//读取输出流
outputStream.write(bytes, 0, len);
}
outputStream.flush(); //刷新
outputStream.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
部分文件后缀对应的content-type
public String getContentType(String suffix) {
String contentType = "";
//转小写
switch (suffix.toLowerCase()) {
case "txt":
contentType = "text/plain";
break;
case "html":
contentType = "text/html";
break;
case "css":
contentType = "text/css";
break;
case "js":
contentType = "text/javascript";
break;
case "json":
contentType = "application/json";
break;
case "xml":
contentType = "application/xml";
break;
case "jpeg":
case "jpg":
contentType = "image/jpeg";
break;
case "png":
contentType = "image/png";
break;
case "gif":
contentType = "image/gif";
break;
case "mp3":
contentType = "audio/mpeg";
break;
case "wav":
contentType = "audio/wav";
break;
case "ogg":
contentType = "audio/ogg";
break;
case "mp4":
contentType = "video/mp4";
break;
case "webm":
contentType = "video/webm";
break;
case "pdf":
contentType = "application/pdf";
break;
case "tiff":
contentType = "image/tiff";
break;
default:
contentType = "application/octet-stream";
break;
}
return contentType;
}
//获取文件后缀
public String getSuffix(String filename) {
int dotIndex = filename.lastIndexOf(".");
return filename.substring(dotIndex + 1);
}