JAVA将文件以流的形式返回
@RequestMapping("/GetFile")
public void getFile(HttpServletRequest request , HttpServletResponse response) throws IOException {
File file = new File("D:\\");
File picFile = null;
for(File f : file.listFiles()){
if(f.getName().contains("DEMO.jpg")){
picFile = new File(f.getPath());
String ext = picFile.getName().substring(picFile.getName().indexOf("."));
if(ext.equals("jpg")){
response.setContentType("image/jpeg");
}else if(ext.equals("JPG")){
response.setContentType("image/jpeg");
}else if(ext.equals("png")){
response.setContentType("image/png");
}else if(ext.equals("PNG")){
response.setContentType("image/png");
}
}
}
InputStream in = new FileInputStream(picFile);
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
byte[] buff =new byte[1024];
int n;
while((n=in.read(buff))!=-1){
outputStream.write(buff,0,n);
}
outputStream.flush();
outputStream.close();
in.close();
}