一般的ServerLet或者maven项目都能使用这个方法,使外网访问自己电脑硬盘中的图片。
方法一:tomcat映射
tomcat->conf->server.xml添加:
<Context path="/files" docBase="/Users/linxz/java/tomcat9/files" reloadable="true"/>
方法二:代码读取流
@RequestMapping("/imgs/{path}")
public void getImage(@PathVariable String path,HttpServletRequest request,HttpServletResponse response){
//获取首页图片显示类
String filePath = "D://imgs/"+path+".png";
System.out.println(filePath);
try {
byte data[] = readFile(filePath);
response.setContentType("image/jpg"); //设置返回的文件类型
OutputStream os = response.getOutputStream();
os.write(data);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 从文件地址,读取文件的Byte数组
* @param filename
* @return
* @throws IOException
*/
public static byte[] readFile(String filename) throws IOException {
if( filename==null || filename.equals("") ){
throw new NullPointerException("无效的文件路径");
}
File file =new File(filename);
long len = file.length();
byte[] bytes = new byte[(int)len];
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
int r = bufferedInputStream.read( bytes );
if (r != len)
throw new IOException("读取文件不正确");
bufferedInputStream.close();
return bytes;
}