这个程序只是为了编码时方便调试用;如果正式服务器运营,建议使用nginx访问mongodb数据库。
一个java的servlet文件(FileCtrl .java):
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFSDBFile;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FileCtrl extends HttpServlet {
private static final long serialVersionUID = -1504839175114429753L;
private Date getDateByString(String format, String dateStr) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.parse(dateStr);
}
private boolean needCache(String ext){//判断文件是否需要缓存。
if(ext == null){
return false;
}
boolean need = false;
String[] arr = {"jpg", "jpeg", "png", "gif", "bmp", "html", "htm", "swf", "mp3", "mp4", "pdf"};
for(String s : arr){
if(s.equals(ext)){
need = true;
break;
}
}
return need;
}
private String getContentType(String ext){
String type = null;
if(ext == null){
type = "application/octet-stream";
}
else if(ext.equals("jpg")){
type = "image/jpeg";
}
else if(ext.equals("jpeg") || ext.equals("png") || ext.equals("gif") || ext.equals("bmp")){
type = "image/" + ext;
}
else if(ext.equals("html") || ext.equals("htm")){
type = "text/html; charset=utf-8";
}
else if(ext.equals("swf")){
type = "application/x-shockwave-flash";
}
else if(ext.equals("mp3")){
type = "audio/x-mpeg";
}
else if(ext.equals("mp4")){
type = "video/mp4";
}
else if(ext.equals("pdf")){
type = "application/pdf";
}
else{
type = "application/octet-stream";
}
return type;
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=utf-8");
String url = URLDecoder.decode(request.getRequestURI(), "utf-8"); //doget方法可以访问带汉字的url
int second = url.indexOf("/files/", 1);
url = url.substring(second + 7);
String[] arr = url.split("/");
DBObject query = new BasicDBObject("filename", arr[2]);
query.put("type", arr[0]);
try {
query.put("publishDate", getDateByString("yyyy-MM-dd", arr[1]));
} catch (ParseException e1) {
System.out.println(e1.getMessage());
}
GridFS fs = new GridFS(mongo.getDB(database));//连接mongodb数据库;细节就不详述。
GridFSDBFile f = fs.getFs().findOne(query);
if(f == null){
PubFun.ajaxPrintC("此文件不存在!", response);
}else{
String ext = null;
int index = arr[2].lastIndexOf(".");
if(index > 0){
ext = arr[2].substring(index+1).toLowerCase();
}
response.setContentType(getContentType(ext));
if(needCache(ext)){
String modifiedSince = request.getHeader("If-Modified-Since");
DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("GMT"));
Date uploadDate = f.getUploadDate();
String lastModified = df.format(uploadDate);
if(modifiedSince != null){
Date modifiedDate = null;
Date sinceDate = null;
try{
modifiedDate = df.parse(lastModified);
sinceDate = df.parse(modifiedSince);
}catch(ParseException e){
System.out.println(e.getMessage());
}
if(modifiedDate.compareTo(sinceDate) <= 0){
response.setStatus(304); //Not Modified
return;
}
}
long maxAge = 10L * 365L * 24L * 60L * 60L; //ten years, in seconds
response.setHeader("Cache-Control", "max-age=" + maxAge);
response.setHeader("Last-Modified", lastModified);
response.setDateHeader("Expires", uploadDate.getTime() + maxAge * 1000L);
}else{
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
}
f.writeTo(response.getOutputStream());
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
可以通过FileCtrl来获取,在web.xml中配置如下:
<servlet>
<servlet-name>files</servlet-name>
<servlet-class>FileCtrl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>files</servlet-name>
<url-pattern>/files/*</url-pattern>
</servlet-mapping>
外部ie访问url: http://127.0.0.1:8080/files/hqsb/2012-02-02/20120224第一版.pdf