一、上传图片到项目文件并添加至数据库中
JDBCTest.java 连接数据库
package petTest.dao;
import java.sql.*;
import petTest.bean.*;
import java.sql.Connection;
public class JDBCTest {
private static String url="jdbc:mysql://localhost:3306/pethospitalmanager?useUnicode=true&characterEncoding=UTF-8"; //防止中文乱码
private static String className="com.mysql.jdbc.Driver";
private static Connection connection = null;
//创建角色
private static String user="petroot";
private static String password="petroot";
public static Connection getConnection() {
try {
Class.forName(className); //加载驱动
connection = DriverManager.getConnection(url, user, password); //创建连接
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
//关闭连接
public static void Close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
try {
if (resultSet != null)
resultSet.close();
if (preparedStatement != null)
preparedStatement.close();
if (connection != null)
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void test() {
System.out.println(JDBCTest.getConnection());
}
}
PhoteDao.java
package petTest.dao;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
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;
/**
* @author Mr Tang
*
*/
public class PhotoDao {
/**
*获取前端的数据集合,将文件打包成File以便后续操作
*/
public static List<FileItem> getRequsetFileItems(HttpServletRequest request,ServletContext servletContext){
boolean isMultipart=ServletFileUpload.isMultipartContent(request);
if(isMultipart) {
DiskFileItemFactory factory = new DiskFileItemFactory();
String str="javax.servelet.context.tempdir";
File repository=(File) servletContext.getAttribute(str);
factory.setRepository(repository);
ServletFileUpload upload=new ServletFileUpload(factory);
try {
return upload.parseRequest(request);
}catch (FileUploadException e) {
// TODO: handle exception
return null;
}
}else {
return null;
}
}
/**
*将文件传到预先设置的绝对路径中,也就是项目里的Images文件夹
*/
public static boolean saveFile(FileItem item,String fileName) {
File savePath=new File("E:\\eclipse\\PetHospitalManager\\WebContent\\Images");
if(!savePath.exists()) {
savePath.mkdirs();
}
List Files = new ArrayList();
DiskFileItemFactory fu =new DiskFileItemFactory ();
File uploadFile=new File(savePath+File.separator+fileName);
try{
item.write(uploadFile);