5.26团队第二阶段冲刺(一)

燃尽图:

任务板:

 

会议图片:

今日任务:找一个合适的模板,并将代码功能嵌套进去,并且学习对于第一阶段未解决上传图片的问题。

明天计划:做之前做的发布寻物启示和失物招领的表单加上上传图片,并且对于信息的展示进行图片的描述显示

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/imgServlet" method="post" enctype="multipart/form-data" onsubmit="return check()">
	ID:<p><input type="text" name="id"  />
	<p><input type="file"  name="file" id="file"   onchange="showPreview(this)" > <br />
    <P><img id="portrait" src="" width="170" height="175">  
	<p><input type="submit" name="submit" value="提交上传" />
</form>
<script type="text/javascript">
function showPreview(source) {
	var file = source.files[0];
	if(window.FileReader) { 
		var fr = new FileReader();
		fr.onloadend = function(e) {
			document.getElementById("portrait").src = e.target.result;
			};
			fr.readAsDataURL(file);  //也是利用将图片作为url读出
			}
	}
function check(){
	var fileInput = document.getElementById("file");
	var files = fileInput.files;


}
</script>  


</body>
</html>

  

package Servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

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 Dao.Dao;
import Entity.FileUploadUtils;

/**文件上传servlet
 * Servlet implementation class imgServlet
 */
@WebServlet("/imgServlet")
public class imgServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public imgServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    Dao dao = new Dao();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//1乱码
//		response.getWriter().append("Served at: ").append(request.getContextPath());
	    request.setCharacterEncoding("utf-8");
	    response.setContentType("text/html;charset=utf-8");
	    
	    String path = request.getServletContext().getRealPath("/upload");//  /指的是项目路径
	    System.out.println(path);
	    File dir = new File(path);
	    if(!dir.exists()) {
	    	dir.mkdirs();//创建
	    }
	    
	    
	    //2处理文件上传
	    
	    
	    //2.1创建磁盘文件工厂
	    DiskFileItemFactory factory = new DiskFileItemFactory();
//	    factory.setSizeThreshold(1024*100);//使用缓存,设置缓存大小100k 默认10k
	    //设置缓存位置
//	    factory.setRepository(new File("d:\..."));
	    
	    
	    //创建文件解析器
	    ServletFileUpload upload = new ServletFileUpload(factory);
	    //判断是否为多分布表单
	    if(!upload.isMultipartContent(request)) {
	    	return;
	    }
	    //解析
	    upload.setHeaderEncoding("utf-8");//解决文件名中文乱码
	    //控制单独文件大小2M
//	    upload.setFileSizeMax(1024*1024*2);
//	    //控制总文件大小
//	    upload.setSizeMax(1024*1025*50);
	    String name = null;
		String value = null;
		String filenameNow = null;
		String ext = null;
		String newfilename = null;
	    try {
			List<FileItem> fileItems = upload.parseRequest(request);//表单中数据
			if(fileItems!=null) {
				
				for(FileItem fileItem : fileItems) {
					//处理表单中的普通数据数据
					if(fileItem.isFormField()) {
					     name = fileItem.getFieldName();
					     
						 if(!name.equals("submit")) {
							 value = fileItem.getString("utf-8");//注意乱码 
						 }
						System.out.println( name + "....." + value);
					}else {//处理文件数据
						//流处理
						InputStream is = fileItem.getInputStream();
						String filename = fileItem.getName();
						String temp[]=filename.split("\\");
					    filenameNow = temp[temp.length-1];

						//如果满zu上传文件
						if(filenameNow==null||filenameNow.trim().equals("")) {
							continue;
						}
						//控制上传文件的类型
						ext = filenameNow.substring(filenameNow.lastIndexOf(".")+1);
						List<String> acceptExts = new ArrayList<String>();
						acceptExts.add("jpg");
						acceptExts.add("png");
						if(!acceptExts.contains(ext)) {
							response.getWriter().write(filenameNow+"不支持此格式文件上传");
							continue;
						}
						newfilename = FileUploadUtils.getNewFilename(filenameNow);
						FileOutputStream fos = new FileOutputStream(dir+"\"+newfilename);
											
						byte[] buf = new byte[1024*4];
						int len = 0;
						while((len=is.read(buf))!=-1) {
							fos.write(buf,0,len);
							
						}
						fos.close();
						is.close();
						
						response.getWriter().write(filenameNow+"LOAD SUCCESS!");
						
					}
					
					
				}
				FileUploadUtils utils = new FileUploadUtils(value,newfilename);
				if(dao.add(utils)) {
					request.setAttribute("message", "添加成功!");
					request.getRequestDispatcher("addresult.jsp").forward(request, response);
				}else {
					request.setAttribute("message", "图书名称重复,请重新输入!");
					request.getRequestDispatcher("add.jsp").forward(request, response);
				}
			}
			
			
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
	    
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

  

package Dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import DBcon.db;
import Entity.FileUploadUtils;


public class Dao {
	public boolean add(FileUploadUtils utils) {
		String sql = "insert into photo1(id,name) values('" + utils.getId() + "','" + utils.getPhotoname()  + "')";
		//创建数据库链接
		Connection conn = db.getConn();
		Statement state = null;
		boolean f = false;
		int a = 0 ;
		
		try {
			state = conn.createStatement();
			a = state.executeUpdate(sql);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//关闭z	连接
			db.close(state, conn);
		}
		
		if (a > 0) {
			f = true;
		}
		return f;
	}
	public ResultSet getAllRs(){
   		String sql="SELECT * from photo1 ORDER BY xuhao desc";
   		Connection conn = db.getConn();
   		ResultSet rs = null;
   		try{
			 Statement state = conn.createStatement();
			 rs=state.executeQuery(sql);
		}
		catch(SQLException e){
			e.printStackTrace();
			}
		return rs;
	}

}

  

package DBcon;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class db {
	public static String db_url = "jdbc:mysql://localhost:3306/info_s";
	public static String db_user = "root";
	public static String db_pass = "z376371066.";
	
	public static Connection getConn () {
		Connection conn = null;
		
		try {
			Class.forName("com.mysql.jdbc.Driver");//加载驱动
			conn = DriverManager.getConnection(db_url, db_user, db_pass);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return conn;
	}
	
	/**
	 * 关闭连接
	 * @param state
	 * @param conn
	 */
	public static void close (Statement state, Connection conn) {
		if (state != null) {
			try {
				state.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void close (ResultSet rs, Statement state, Connection conn) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if (state != null) {
			try {
				state.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) throws SQLException {
		Connection conn = getConn();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql ="select * from book";
		pstmt = conn.prepareStatement(sql);
		rs = pstmt.executeQuery();
		if(rs.next()){
			System.out.println("空");
		}else{
			System.out.println("不空");
		}
	}


}

  

package Entity;

import java.util.UUID;

public class FileUploadUtils {
	private String id;
	private String photoname;

	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPhotoname() {
		return photoname;
	}
	public void setPhotoname(String photoname) {
		this.photoname = photoname;
	}
	public static String getNewFilename(String oldfilename) {
		String uuid = UUID.randomUUID().toString();//全球通用唯一表示
		System.out.println(uuid);
		return uuid+"_"+oldfilename;
	}
	public FileUploadUtils(String id, String name) {
		this.id = id;
		this.photoname = name;
	
	}
	

}

  

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<jsp:useBean id="dao" class="Dao.Dao" scope="page"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<table>
      <tr align="center" valign="middle" bgcolor="#CCCCCC" height="22">
        <td>照片名称</td>
		<td>照片显示</td>
      <%
        ResultSet rs=dao.getAllRs();
        if(rs==null){
      %>
      <tr align="center" valign="middle"><td colspan="4">没有记录显示!</td>
      </tr>
      <%
        }
        else{
        	 if(rs.next()){
      %>
      <tr align="center" valign="middle" height="22">
        <td>222222</td>  	
        <td><%=rs.getString("id") %></td>  		 
        <td><img src="upload<%=rs.getString("name") %>" width="150px";height="100px"></td>                 	
      </tr>
      <%
        	}
        	 if(rs.next()){
        	      %>
        	      <tr align="center" valign="middle" height="22">
        	        <td>4444</td>  	
        	        <td><%=rs.getString("id") %></td>  		 
        	        <td><img src="upload<%=rs.getString("name") %>" width="150px";height="100px"></td>                 	
        	      </tr>
        	      <%
        	        	}
        	 if(rs.next()){
       	      %>
       	      <tr align="center" valign="middle" height="22">
       	        <td>uuuuu</td>  	
       	        <td><%=rs.getString("id") %></td>  		 
       	        <td><img src="upload<%=rs.getString("name") %>" width="150px";height="100px"></td>                 	
       	      </tr>
       	      <%
       	        	}
        	 
        }
      %>
</table>
**********************<br>
<input type="button" value="返回功能界面" onclick="window.location.href='add.jsp';"/><br>
**********************<br>
</body>
</html>

  

原文地址:https://www.cnblogs.com/ruan1705/p/11061737.html