---
title: "获取服务器硬盘图片"
author: "erwin_king"
date: "2011-08-10T12:15:07Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2011-08-10T12:15:07Z"
id: 1144497
url: "https://erwin-king.iteye.com/blog/1144497"
---

private void getImage(HttpServletRequest request, HttpServletResponse response, String filePath)  
   throws ServletException, IOException {  
  // 禁止缓存  
  response.setHeader("Pragma", "No-cache");  
  response.setHeader("Cache-Control", "No-cache");  
  response.setDateHeader("Expires", 0);  
  // 指定生成的响应是图片  
  ServletOutputStream out = response.getOutputStream();

  String type = FilenameUtils.getExtension(filePath);  
  if (StringUtils.isEmpty(type))  
   type = "PNG";  
  byte\[] bytData = new byte\[] {};  
  if (null != filePath) {

   bytData = getBytesFromFile(new File(filePath));

   if (bytData != null) {  
    response.setContentLength(bytData.length);  
    response.setContentType("image/" + type);  
    System.out.println("\_bytData.length===&gt;" + bytData.length);  
    out.write(bytData);  
    out.flush();  
   }  
  }  
 }

 /\**  
  *  
  * @param f File  
  * @return byte\[]  
  \*/  
 public static byte\[] getBytesFromFile(File f) {

  System.out.println("File==&gt;" + f.getPath());  
  if (f == null) {  
   return null;  
  }

  try {  
   FileInputStream stream = new FileInputStream(f);  
   ByteArrayOutputStream out = new ByteArrayOutputStream(1000);

   byte\[] b = new byte\[1000];  
   int n;  
   while ((n = stream.read(b)) != -1) {  
    out.write(b, 0, n);  
   }  
   stream.close();  
   out.close();

   return out.toByteArray();  
  } catch (IOException e) {  
   e.printStackTrace();  
  }

  return null;  
 }