java图片上传总结
主要的代码,作用:上传文件
package cn.ygc.servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import cn.ygc.dao.DBAgent;
import cn.ygc.modal.Result;
@WebServlet("/register")
//用户注册页
public class Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public Servlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
System.out.println("get");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out=response.getWriter();
out.print("<html><meta charset='utf-8'>");
DiskFileItemFactory factory = new DiskFileItemFactory();
// Configure a repository (to ensure a secure temp location is used)
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
Map<String,String> map=new HashMap<String,String>();
// Parse the request
try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter =items.iterator();
while(iter.hasNext()){
FileItem item=iter.next();
//判断是否为普通文件
if(item.isFormField()){
//键值对骚操作
map.put(item.getFieldName(),new String(item.getString().getBytes("iso-8859-1"),"utf-8") );
}
else{
//获取文件类型
String type=item.getContentType();
if(type.equals("image/jpeg")||type.equals("image/png")){
long size=item.getSize();
//获取文件大小
if(size>4*1024*1024){
out.print("<script>alert('请上传小于4MB的图片');window.history.go(-1);</script>");
return;
}else{
//获取apache-tomcat的image的路径
String dir=this.getServletContext().getRealPath("image");
String filename=new Date().getTime()+".jpg";
//文件对象:路径+文件名
File file=new File(dir+"\\"+filename);
//写操作:路径+文件名,item代表该文件
item.write(file);
map.put("filename", filename);
}
}else{
out.print("<html><meta charset='utf-8'><script>alert('请上传有效格式的图片');window.history.go(-1);</script></html>");
return;
}
}
}
//添加到数据库:
Result r=DBAgent.register(map);
if(r.getCode()==0){
out.print("<html><meta charset='utf-8'><script>alert('添加成功');window.location.href='page-login.jsp'</script></html>");
}else{
out.print("<html><meta charset='utf-8'><script>alert('添加失败!!原因:"+r.getMessage()+"');window.history.go(-1);</script></html>");
}
// for(Map.Entry<String, String> e:map.entrySet()){
// System.out.println(e.getKey()+":"+e.getValue());
// }
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.print("</html>");
out.flush();//把缓存区内容推出去
out.close();//关闭缓冲区
}
}
次要的代码,作用:往数据库插入数据
public static Result register(Map<String,String> map){
Result rs=null;
String sql=null;
Connection con=getConnection();
try {
sql="insert into admin(username,realname,phone,password,email,img,typeid) values(?,?,?,?,?,?,?)";
PreparedStatement pstm=con.prepareStatement(sql);
pstm.setString(1, map.get("username"));
pstm.setString(2, map.get("realname"));
pstm.setString(3, map.get("phone"));
pstm.setString(4, map.get("password"));
pstm.setString(5, map.get("email"));
pstm.setString(6,map.get("filename"));
pstm.setInt(7,Integer.parseInt(map.get("typeid")));
pstm.execute();
} catch (NumberFormatException e) {
e.printStackTrace();
return new Result(-2,"数据格式不对!!");
} catch (SQLException e) {
e.printStackTrace();
return new Result(-3,"数据操作异常!!");
}
rs=new Result(0,"success");
return rs;
}
次要代码,作用报错误码和信息
package cn.ygc.modal;
public class Result {
private int Code;
private String Message;
public int getCode() {
return Code;
}
public void setCode(int code) {
Code = code;
}
public String getMessage() {
return Message;
}
public void setMessage(String message) {
Message = message;
}
public Result(int code, String message) {
super();
Code = code;
Message = message;
}
public Result() {
super();
}
}
上传流程: