<%@ page contentType="text/html;charset=gb2312"%><%@page import="cn.js.fan.util.*"%><%@page import="cn.js.fan.web.*"%><%@page import="com.redmoon.forum.*"%><%@page import="java.util.*"%><%@page import="java.io.*"%><%@page import="java.net.*"%><jsp:useBean id="privilege" scope="page" class="com.redmoon.forum.Privilege"/><%
if (!privilege.isUserLogin(request)) {
	if (!ForumDb.getInstance().canGuestSeeAttachment()) {
		response.sendRedirect("../info.jsp?op=login&info=" + StrUtil.UrlEncode(SkinUtil.LoadString(request, "info_please_login")));
		return;	
	}
}

int msgId = ParamUtil.getInt(request, "msgId");
int attachId = ParamUtil.getInt(request, "attachId");

MsgDb md = new MsgDb();
md = md.getMsgDb(msgId);

if (md==null || !md.isLoaded()) {
	out.print("<meta http-equiv='Content-Type' content='text/html; charset=gb2312'>");
	out.println("Topic not found!");
	return;
}

Attachment att = md.getAttachment(attachId);

// response.setContentType(MIMEMap.get(StrUtil.getFileExt(att.getDiskName())));
// response.setContentType(MIMEMap.get(att.getExt()));
// response.setHeader("Content-disposition","filename=" + StrUtil.GBToUnicode(att.getName()));

// 以询问下载的方式打开，会覆盖父窗口
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition","attachment; filename=" + StrUtil.GBToUnicode(att.getName()));

BufferedInputStream bis = null;
BufferedOutputStream bos = null;

try {
	bis = new BufferedInputStream(new FileInputStream(att.getFullPath()));
	bos = new BufferedOutputStream(response.getOutputStream());
	
	byte[] buff = new byte[2048];
	int bytesRead;
	
	while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
	bos.write(buff,0,bytesRead);
	}

} catch(final IOException e) {
	System.out.println( "IOException: " + e );
} finally {
	if (bis != null)
		bis.close();
	if (bos != null)
		bos.close();
}

att.setDownloadCount(att.getDownloadCount() + 1);
att.save();
%>