这个暑假在家搭建服务器,其中遇到了问题:Tomcat放在一个盘,多媒体资源放在另外一个盘。现在要求浏览器能够通过访问servlet访问到多媒体资源。
一开始我在servlet中直接用io流读文件,然后读多少就发送多少,前端直接访问servlet,视频、音乐能够播放,但是不能拖进。为此,尝试了各种方法,并结合网络资料,花了好几天时间最终实现此功能,部分内容从网上摘取,到底是从哪里找的已经成了迷,特有此篇来记录方法,方便自己和读者以后使用。
后端代码:
//servlet的doGet方法中如下:
String path=request.getParameter("path");
path=URLDecoder.decode(path,"utf-8");
String ftype=path.substring(path.lastIndexOf("."));
File f=new File(path);
String fileName=f.getName();
System.out.println("path: "+path+"\n"+"fileName: "+fileName);
FileInputStream fis=new FileInputStream(path);
ServletOutputStream fos=response.getOutputStream();
//getBytesFromFile(Fine f)该方法将文件读到内存中,并返回byte[]型对象,Tomcat对JVM的内存大小有设置,如果文件太大,会发生错误。
byte[] bb=getBytesFromFile(f);
//下面两个头的设置是必须的,此响应头设置文件长度,下面的头设置接收的“类”(ranges是类的意思)。
//如果缺少这两个头,网页端的播放将会卡顿,而且不能拖进。
response.setContentLength(bb.length);
response.setHeader("Accept-Ranges", "bytes");
byte[] content = new byte[1024];
BufferedInputStream is = new BufferedInputStream(new ByteArrayInputStream(bb));
OutputStream os = response.getOutputStream();
while (is.read(content) != -1) {
os.write(content);
}
fis.close();
private static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
long length = file.length();
if (length > Integer.MAX_VALUE) {
return null;
}
byte[] bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while ((offset < bytes.length) && ((numRead = is.read(bytes, offset, bytes.length - offset)) >= 0)) {
offset += numRead;
}
if (offset < bytes.length) {
throw new IOException("Could not completely read file " + file.getName());
}
is.close();
return bytes;
}
前端
前端需要在请求发path——服务器端文件地址。