package com.fileserver;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
/**
*用于支持视频的拖动
* @author Gabriel
*/
public class PartialRender {
private ServletContext sc;
private HttpServletResponse response;
private int range = -1;
public PartialRender(ServletContext sc,HttpServletResponse response,int range){
this.sc = sc;
this.response = response;
if(range>=0){
this.range = range;
}
}
/**
* 输出文件流
* @param file 输出文件位置
*/
public void doRender(File file){
String contentType = sc.getMimeType(file.getName());
if(contentType==null)
contentType = Const.DEFAULT_FILE_CONTENT_TYPE; //"application/octet-stream"
int fileSize = (int)file.length();
response.setContentType(contentType);
if(range!=-1){
response.setHeader("Content-Range","bytes "+ range+"-"+(fileSize-1)+"/"+fileSize);
response.setContentLength(fileSize-range);
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
}else{
response.setContentLength(fileSize);
response.setStatus(HttpServletResponse.SC_OK);
}
InputStream is = null;
OutputStream os = null;
try{
byte[] buf = new byte[1024];
is = new FileInputStream(file);
os = response.getOutputStream();
if(range>0){
is.skip(range);
}
int len;
while((len=is.read(buf))!=-1){
os.write(buf, 0, len);
}
os.flush();
}catch (Exception e) {
//当终止下载或者播放视频时会抛出异常
}finally{
if(is!=null)
try {
is.close();
} catch (IOException e1) {
}
if(os!=null)
try {
os.close();
} catch (IOException e1) {
}
}
}
}