public class UpLoadServlet extends HttpServlet {
private final int BUFFERSIZE = 1024 * 8;
private final String splitLine = File.separator;
private String tempAttachmentFileName;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//得到附件的路径
HttpSession session = request.getSession(false);
com.jetmail.User.Session mailSession = (com.jetmail.User.Session)session.getAttribute("mailSession");
com.jetmail.Tool.Config mailConfig = com.jetmail.Tool.Config.getInstance();
//计算能够上传附件的大小
int maxLen = mailConfig.attachMentSize * 1024 * 1024;
String attachmentPath = mailConfig.tempFolder + splitLine;
attachmentPath = attachmentPath + mailSession.getDomain() + splitLine;
attachmentPath = attachmentPath + mailSession.getUserName() + splitLine;
attachmentPath = attachmentPath + mailConfig.attachmentFolder + splitLine;
tempAttachmentFileName = mailSession.getDomain() + '-' + mailSession.getUserName();
//得到附件
ServletOutputStream out = response.getOutputStream();
int contentLen = request.getContentLength();
if(contentLen < maxLen) {
String contentType = request.getContentType();
String boundary = getBoundary(contentType);
ServletInputStream in = request.getInputStream();
FileOutputStream fou = null;
byte[] b = new byte[BUFFERSIZE];
int result;
try {
result = in.readLine(b,0,b.length); //读取boundary
result = in.readLine(b,0,b.length); //读取Content-Disposition
String upLoadFileName = getUpLoadFileName(new String(b,0,result));
fou = new FileOutputStream(attachmentPath + tempAttachmentFileName);
result = in.readLine(b,0,b.length); //读取Content-Type;
result = in.readLine(b,0,b.length); //读取空行;
int totalRead = 0;
result = in.readLine(b,0,b.length);
while((new String(b,0,result)).trim().indexOf(boundary) == -1) {
totalRead += result;
fou.write(b,0,result);
result = in.readLine(b,0,b.length);
}
out.println(totalRead);
fou.close();
in.close();
//处理文件
dealFile(upLoadFileName,totalRead,attachmentPath);
} catch(Exception ex) {
System.out.print(ex.toString());
}
}
response.sendRedirect("/jsp/upload.jsp");
}