privatemiao
Posts: 17
|
Posted: 01/19/2007, 3:19 AM |
|
code f:
/**
* 实现文件上传 包括取得参数 按照顺序
* @author Love Me
*/
package forum.com;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
public class UploadBean {
private ServletInputStream is = null;
private String fileName = null;
private String boundary = null;
private String filePath = null;
public UploadBean(HttpServletRequest request) {
this.boundary = request.getContentType();
this.boundary = "--" + this.boundary.substring(this.boundary.indexOf("=") + 1, this.boundary.length());
try {
this.is = request.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getParameter(String name){
String line = null;
byte[]buffer = new byte[1024];
int count = 0;
try {
while((count = is.readLine(buffer, 0, 1024)) != -1){
// System.out.println("2");
line = new String(buffer, 0, count);
if (line.indexOf("name=\""+name+"\"") > 0){
// System.out.println("3");
break;
}
}
return getMyParameter();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private String getMyParameter(){
byte[]buffer = new byte[1024];
int count = 0;
String line = null;
String data = "";
boolean flag = true;//第一次
//跳过空行
try {
is.readLine(buffer, 0, 1024);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
while((count = is.readLine(buffer, 0, 1024)) != -1){
line = new String(buffer, 0, count);
//文档末尾
if ((line.indexOf(this.boundary) == 0) && count == this.boundary.length() + 4){
// System.out.println("文档末尾结束");
break;
}
//段落结束
if ((line.indexOf(this.boundary) == 0) && count == this.boundary.length() + 2){
// System.out.println("段落结束结束");
break;
}
//自己控制 空行
if (flag){
line = line.substring(0, line.length() - 2);
flag = !flag;
}else{
line = line.substring(0, line.length() - 2);
line = "\r\n" + line;
}
data += line;
// System.out.println("Amount: " + amount);
// System.out.println("NewData: " + data);
}
try{
return data;
}catch(Exception e){
return null;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 根据 name 找到 filename(定位) 返回 fileName
* @author Love Me
* @return fileName
*/
public String getFileName(String name){
String line = null;
byte[]buffer = new byte[1024];
int count = 0;
try {
while((count = is.readLine(buffer, 0, 1024)) != -1){
line = new String(buffer, 0, count);
if (line.indexOf("name=\""+name+"\"") > 0){
fileName = line.substring(line.lastIndexOf("\\") + 1, line.length() - 3);
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println("得到的文件名为: " + fileName);
if (fileName.lastIndexOf('.') < 0){
return null;
}
return fileName;
}
/**
* 写文件
*
*/
public void store(){
byte[]buffer = new byte[1024];
int count = 0;
FileOutputStream os = null;
String line = null;
if((this.fileName == null) || (this.fileName.length() < 1)){
// System.out.println("未指定文件名");
return;
}
if((this.filePath == null) || (this.filePath.length() < 1)){
// System.out.println("未指定路径");
return;
}
try {
os = new FileOutputStream(this.filePath + this.fileName);
while((count = is.readLine(buffer, 0, 1024)) != -1){
line = new String(buffer, 0, count);
if (line.indexOf("Content-Type") >= 0){
is.readLine(buffer, 0, 1024);
continue;
}
//文档末尾
if ((line.indexOf(this.boundary) == 0) && count == this.boundary.length() + 4){
// System.out.println("文档末尾结束");
break;
}
//段落结束
if ((line.indexOf(this.boundary) == 0) && count == this.boundary.length() + 2){
// System.out.println("段落结束结束");
break;
}
//自己控制 空行
// if (flag){
// os.write(buffer, 0, count - 2);
// flag = !flag;
// }else{
// os.write("\r\n".getBytes());
// os.write(buffer, 0, count - 2);
// }
os.write(buffer, 0, count);
}
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if (os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 以新的文件名写文件
* @author Love Me
* @param fileName
*/
public void setFilename(String fileName){
this.fileName = fileName;
}
public void setFilePath(String filePath){
this.filePath = filePath;
}
public void close(){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
_________________
me was me |
|
|
privatemiao
Posts: 17
|
Posted: 01/19/2007, 3:20 AM |
|
you can use it like this:
package forum.server;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import forum.ConnectionManager;
import forum.bean.Customer;
import forum.com.Methods;
import forum.com.UploadBean;
public class Register extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) {
UploadBean upload = null;
Customer customer = null;
try {
request.setCharacterEncoding("GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// ÑéÖ¤ÉÏ´«Îļþ´óС
if (request.getContentLength() > 0.5 * 1024 * 1024) {
try {
response.sendRedirect("register.jsp?errormessage=BigSize");
return;
} catch (IOException e) {
e.printStackTrace();
}
return;
}
upload = new UploadBean(request);
customer = new Customer();
// //////////////////ÉèÖòÎÊý/////////////
// 1.customerID
customer.setCustomerID(Methods.getSerialID());
// 2.username
customer.setUserName(Methods.convertNullToNull(upload
.getParameter("username")));
if (!validateUserName(customer.getUserName())) {
try {
response.sendRedirect(
"register.jsp?errormessage=TheUserNameHadExist");
return;
} catch (IOException e) {
e.printStackTrace();
}
return;
}
// 3.password
customer.setPassword(Methods.convertNullToNull(upload
.getParameter("password")));
// 4.mail
customer
.setMail(Methods.convertNullToNull(upload.getParameter("mail")));
if ((!validateCustomerParameter(customer))
|| (!validateMail(customer.getMail()))) {
try {
response.sendRedirect(
"register.jsp?errormessage=TheMailHadExistOrParameterError&username="
+ customer.getUserName());
return;
} catch (IOException e) {
e.printStackTrace();
}
return;
}
// 5.registered
customer.setRegistered(Methods.GETCURTIME);
// 6.avatar(filename)
String __fileType = null;
__fileType = Methods.convertNullToNull(upload.getFileName("filename"));
if (__fileType.length() > 0) {// ÎļþÊÇ·ñ´æÔÚ
__fileType = __fileType.substring(__fileType.lastIndexOf(".") + 1);// µÃµ½Îļþ¸ñʽ
// Ñé֤ͼƬ¸ñʽ
if (!validatePicType(__fileType)) {
upload.close();
try {
response.sendRedirect(
"register.jsp?errormessage=FileTypeError&username="
+ customer.getUserName() + "&mail="
+ customer.getMail());
return;
} catch (IOException e) {
e.printStackTrace();
}
return;
}
customer.setAvatar(customer.getCustomerID() + "." + __fileType);
upload.setFilePath(Methods.AVATAR_PATH);
upload.setFilename(customer.getAvatar());
upload.store();
}
// 7.¸öÈËÇ©Ãû
customer.setSignature(Methods.ConvertSpaceChars(Methods.convertNullToNull(upload
.getParameter("signature"))));
String __isNotify = null;
__isNotify = Methods.convertNullToNull(upload.getParameter("isnotify"));
if (__isNotify.length() > 0) {
customer.setIsnotify(1);// ͬÒâ
} else {
customer.setIsnotify(0);
}
// 8.µÇ½ʱ¼ä
customer.setLogon(Methods.GETCURTIME);
upload.close();
// //////////////////ÉèÖòÎÊý½áÊø/////////////
String url = null;
if (!execute(customer)){
if (customer.getAvatar().length() > 0){
delThePicture(Methods.AVATAR_PATH + customer.getAvatar());
}
url = "register.jsp?errormessage=RegisterError&username=" + customer.getUserName() + "&mail=" + customer.getMail() + "&signature=" + customer.getSignature();
}else{
request.getSession().setAttribute("user", customer.getCustomerID());
url = "index.jsp?errormessage=RegisterSuccess";
}
try {
request.getRequestDispatcher(url).forward(request, response);
} catch (IOException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
}
}
/**
* Ñé֤ͼƬ¸ñʽ
*
* @param fileType
* @return
*/
private boolean validatePicType(String fileType) {
if ((fileType.equalsIgnoreCase("jpg"))
|| (fileType.equalsIgnoreCase("gif"))) {
return true;
}
return false;
}
/**
* ÑéÖ¤Óû§ÃûÊÇ·ñ´æÔÚÁË
*
* @param userName
* @return false if the username had exist
*/
private boolean validateUserName(String userName) {
ConnectionManager cm = null;
Connection con = null;
PreparedStatement prepStmt = null;
ResultSet rs = null;
String strSql = null;
boolean flag = false;
cm = new ConnectionManager("forum.properties");
con = cm.getConnection();
strSql = "select * from customers where username = '" + userName + "'";
try {
prepStmt = con.prepareStatement(strSql);
rs = prepStmt.executeQuery();
if (rs.next()) {
flag = false;
} else {
flag = true;
}
cm.closeResultSet(rs);
cm.closePrepStmt(prepStmt);
cm.closeConnection(con);
return flag;
} catch (SQLException e) {
e.printStackTrace();
} finally {
cm.closeAllDB(con, prepStmt, rs);
}
return false;
}
/**
* ÑéÖ¤ÓÊÏäÊÇ·ñ´æÔÚÁË
*
* @param userName
* @return false if the username had exist
*/
private boolean validateMail(String mail) {
ConnectionManager cm = null;
Connection con = null;
PreparedStatement prepStmt = null;
ResultSet rs = null;
String strSql = null;
boolean flag = false;
cm = new ConnectionManager("forum.properties");
con = cm.getConnection();
strSql = "select * from customers where username = '" + mail + "'";
try {
prepStmt = con.prepareStatement(strSql);
rs = prepStmt.executeQuery();
if (rs.next()) {
flag = false;
} else {
flag = true;
}
cm.closeResultSet(rs);
cm.closePrepStmt(prepStmt);
cm.closeConnection(con);
return flag;
} catch (SQLException e) {
e.printStackTrace();
} finally {
cm.closeAllDB(con, prepStmt, rs);
}
return false;
}
private boolean validateCustomerParameter(Customer customer) {
if (customer.getUserName().length() < 1) {
return false;
}
if (customer.getPassword().length() < 1) {
return false;
}
if (customer.getMail().length() < 1) {
return false;
}
return true;
}
/**
* Êý¾Ý¿â²åÈë
*
* @param customer
* @return false if insert faild
*/
private boolean execute(Customer customer) {
ConnectionManager cm = null;
Connection con = null;
PreparedStatement prepStmt = null;
String strSql = null;
int flag = 0;
cm = new ConnectionManager("forum.properties");
con = cm.getConnection();
strSql = "insert into customers (customerid, username, password, mail, registered, avatar, signature, isnotify, logon) values ("
+ "'"
+ customer.getCustomerID()
+ "', '"
+ customer.getUserName()
+ "', '"
+ customer.getPassword()
+ "', '"
+ customer.getMail()
+ "', "
+ customer.getRegistered()
+ ", '"
+ customer.getAvatar()
+ "', '"
+ customer.getSignature()
+ "', "
+ customer.getIsnotify() + ", " + customer.getLogon() + ")";
// System.out.println("Register: " + strSql);
try {
prepStmt = con.prepareStatement(strSql);
flag = prepStmt.executeUpdate();
cm.closePrepStmt(prepStmt);
cm.closeConnection(con);
if (flag == 1){
return true;
}else{
return false;
}
} catch (SQLException e) {
// e.printStackTrace();
return false;
}finally{
cm.closeAllDB(con, prepStmt);
}
}
/**
* Èç¹ûÊý¾Ý¿â²åÈëʧ°Ü Ôòɾ³ýͼƬ
* @param args
*/
private void delThePicture(String avatar){
File f = null;
f = new File(avatar);
if (f.isFile()){
f.delete();
}
}
public static void main(String[] args) {
}
}
_________________
me was me |
|
|
LH_13
Posts: 30
|
Posted: 01/19/2007, 3:28 AM |
|
why you do not use standart CCS fileUploadComonent???
It allow all neede features.
Disabe size control is musch easy than write new own...
_________________
Sorry my english! |
|
|
privatemiao
Posts: 17
|
Posted: 01/19/2007, 3:35 AM |
|
the standart upload com need bigger memory and slowness speed
it less read the stream twice, but my com read the stream one time and less memory .
you can see it
_________________
me was me |
|
|
|