publicvoid doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("GBK");
request.setCharacterEncoding("GBK");
response.setContentType("text/html");
String URL ="jdbc:mysql://localhost:3306/test?user=root&"
+"password=admin&useUnicode=true&characterEncoding=gbk";
Connection conn =null;
Statement stmt =null;
// 判断提交过来的表单是否为文件上传表单
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
String name =null;
String fileName =null;
String path =null;
if (isMultipart) {
// 构造文件上传处理对象
FileItemFactory factory =new DiskFileItemFactory();
ServletFileUpload upload =new ServletFileUpload(factory);
Iterator items;
try {
// 解析出表单中提交的所有文件内容
items = upload.parseRequest(request).iterator();
while (items.hasNext()) {
FileItem item = (FileItem) items.next();
name = item.getName();
// 获取文件名
fileName = name.substring(name.lastIndexOf('\\') +1, name
.length());
// 获取文件上传后的存储路径(上传后的文件将存储到当前应用项目的file文件夹中)
// File.separatorChar相当于/
String realPath = request.getRealPath("upload");
path = realPath + File.separator + fileName;
File uploadFile =new File(path);
item.write(uploadFile);
String sql ="insert into file(filename,filepath) value('"+fileName+"','"+path+"')";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL);
stmt = conn.createStatement();
stmt.execute(sql);
PrintWriter out = response.getWriter();
out.println("<p align='center'><font size='2'>上传的文件为:"
+ name +"<br>");
out.println("<font size='2'>保存的路径是:"+ path +"</p>");
}
} catch (Exception e) {
}
}
}