package lw;
import java.util.*;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class UploadServlet extends HttpServlet {
String username,writername,lwname,time,topic;
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,IOException
{
response.setContentType("text/html;charset=GBK");
PrintWriter out = response.getWriter();
//设置保存上传文件的目录
String uploadDir = getServletContext().getRealPath("/upload");
if (uploadDir == null)
{
out.println("无法访问存储目录!");
return;
}
File fUploadDir = new File(uploadDir);
if(!fUploadDir.exists())
{
if(!fUploadDir.mkdir())
{
out.println("无法创建存储目录!");
return;
}
}
if (!DiskFileUpload.isMultipartContent(request))
{
out.println("只能处理multipart/form-data类型的数据!");
return ;
}
DiskFileUpload fu = new DiskFileUpload();
//最多上传200M数据
fu.setSizeMax(1024 * 1024 * 200);
//超过1M的字段数据采用临时文件缓存
fu.setSizeThreshold(1024 * 1024);
//采用默认的临时文件存储位置
//fu.setRepositoryPath(...);
//设置上传的普通字段的名称和文件字段的文件名所采用的字符集编码
fu.setHeaderEncoding("gb2312");
//得到所有表单字段对象的集合
List fileItems = null;
try
{
fileItems = fu.parseRequest(request);
}
catch (FileUploadException e)
{
out.println("解析数据时出现如下问题:");
e.printStackTrace(out);
return;
}
//处理每个表单字段
Iterator i = fileItems.iterator();
while (i.hasNext())
{
FileItem fi = (FileItem) i.next();
if (fi.isFormField())
{
String content = fi.getString("GB2312");
String fieldName = fi.getFieldName();
request.setAttribute(fieldName,content);
}
else
{
try
{
String pathSrc = fi.getName();
/*如果用户没有在FORM表单的文件字段中选择任何文件,
那么忽略对该字段项的处理*/
if(pathSrc.trim().equals(""))
{
continue;
}
int start = pathSrc.lastIndexOf('\\');
String fileName = pathSrc.substring(start + 1);
File pathDest = new File(uploadDir, fileName);
fi.write(pathDest);
String fieldName = fi.getFieldName();
request.setAttribute(fieldName, fileName);
String contentType = fi.getContentType();
if(contentType.equals("application/pdf"))//如果fileName为null,即没有上传文件
{
File uploadedFile = new File(uploadDir,fileName);
try
{
fi.write(uploadedFile);
}
catch (Exception e)
{
e.printStackTrace();
}
//response.sendRedirect("/thesis_sys/up_suc.jsp");
}
else
response.sendRedirect("fail.jsp");
}
catch (Exception e)
{
out.println("存储文件时出现如下问题:");
e.printStackTrace(out);
return;
}
finally //总是立即删除保存表单字段内容的临时文件
{
fi.delete();
}
}
}
response.sendRedirect("userindex.jsp");
}
/*String username;
String writername;
String lwname;
String time;
String topic;
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,IOException
{
uploadadd(request,response);
}
//显示处理结果
//out.println("用户:" + request.getAttribute("author") + "<br>");
//out.println("来自:" + request.getAttribute("company") + "<br>");
/*将上传的文件名组合成"file1,file2"这种形式显示出来,如果没有上传
*任何文件,则显示为"无",如果只上传了第二个文件,显示为"file2"。*/
//StringBuffer filelist = new StringBuffer();
//String file1 = (String)request.getAttribute("file1");
//makeUpList(filelist,file1);
//String file2 = (String)request.getAttribute("file2");
//makeUpList(filelist,file2);
//out.println("成功上传的文件:" +
//(filelist.length()==0 ? "无" : filelist.toString()));
/*public void uploadadd(HttpServletRequest request,
HttpServletResponse response) throws IOException,ServletException
{
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
DiskFileItemFactory dff = new DiskFileItemFactory();// 创建该对象
dff.setSizeThreshold(1024000);// 指定在内存中缓存数据大小,单位为byte
ServletFileUpload sfu = new ServletFileUpload(dff);// 创建该对象
sfu.setFileSizeMax(5000000);// 指定单个上传文件的最大尺寸(单个文件大小不超过5M)
sfu.setSizeMax(20000000);// 指定一次上传多个文件的总尺寸(总文件大小不超过20M)
try{
FileItemIterator fii = sfu.getItemIterator(request);// 解析request
}catch(FileUploadException e){
e.printStackTrace();
}
List uploaditems = null;
try{
uploaditems = sfu.parseRequest(request);
}catch(FileUploadException e){
e.printStackTrace();
}
for(int i=0;i<uploaditems.size();i++){
FileItem item = (FileItem)uploaditems.get(i);
if(item.isFormField()){
String name = item.getFieldName();
String value = item.getString("GBK");
username = item.getString("username");//此处即为你想要的值,相当于request.getParameter("username");
writername = item.getString("writername");
lwname = item.getString("lwname");
time = item.getString("time");
topic = item.getString("topic");
request.setAttribute("username",username);
request.setAttribute("writername",writername);
request.setAttribute("lwname",lwname);
request.setAttribute("time",time);
request.setAttribute("topic",topic);
}
}
try
{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
String url="jdbc:microsoft:sqlserver://Localhost:1433;DatabaseName=dissertation";
String user="sa";
String password="900315";
java.sql.Connection conn=DriverManager.getConnection(url,user,password);
String sql="insert into lwinformation(username,writer,name,time,topic) values('"+username+"','"+writername+"','"+lwname+"','"+time+"','"+topic+"')";
PreparedStatement stmt=conn.prepareStatement(sql);
stmt.executeUpdate();
stmt.close();
conn.close();
out.println("插入成功");
}
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
out.println("connect sql server error 01!");
e.printStackTrace();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
out.println("connect sql server error 02!");
e.printStackTrace();
}
response.sendRedirect("userindex.jsp");
}*/
/**
*将一段字符串追加到一个结果字符串中。如果结果字符串的初始内容不为空,
*在追加当前这段字符串之前先最加一个逗号(,)。在组合sql语句的查询条件时,
*经常要用到类似的方法,第一条件前没有"and",而后面的条件前都需要用"and"
*作连词,如果没有选择第一个条件,第二个条件就变成第一个,依此类推。
*
*@param result 要将当前字符串追加进去的结果字符串
*@param fragment 当前要追加的字符串