2018-07-28 10:36

根据波总意见改造,Constant.STATIC_FILE_PREFIX即是"/static/file"
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jfinal.handler.Handler;
import com.lyw.base.config.Constant;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
* author: Andersen
* mail:
* Date: 2018/7/27 17:24
*/
public class FileHandler extends Handler {

@Override
public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
if (target.startsWith(Constant.STATIC_FILE_PREFIX)) {
String view = target.substring(Constant.STATIC_FILE_PREFIX.length());
response.setContentType("application/octet-stream;charset=UTF-8");
FileInputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream(Constant.UPLOAD_DEFAULT_PATH + view);
outputStream=new BufferedOutputStream(response.getOutputStream());
byte[] buf = new byte[512];
int len=-1;
while((len=inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
inputStream.close();
outputStream.flush();
outputStream.close();
isHandled[0] = true;
return;
} catch (Exception e) {
e.printStackTrace();
} finally {
if(null != inputStream){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != outputStream){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
next.handle(target, request, response, isHandled);
}

}