private static final String CONTENT_TYPE = "text/html; charset=GB2312";
// private String uploadPath = "e:\\upload\\"; // 上传文件的目录
//private String tempPath = "e:\\temp\\"; // 临时文件目录
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("ffffffffffff");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
try {
DiskFileUpload fu = new DiskFileUpload();
// 设置最大文件尺寸,这里是4MB
fu.setSizeMax(4194304);
// 设置缓冲区大小,这里是4kb
fu.setSizeThreshold(4096);
// 设置临时目录:
// fu.setRepositoryPath(tempPath);
// 得到所有的文件:
List fileItems = fu.parseRequest(request);
Iterator i = fileItems.iterator();
// 依次处理每一个文件:
while(i.hasNext()) {
FileItem fi = (FileItem)i.next();
// 获得文件名,这个文件名包括路径:
String filepath = fi.getName();
// 在这里可以记录用户和文件信息
if(null!=filepath && !filepath.equals("") && filepath.length()>1){
String fileName=getFileName(filepath);
System.out.println("fileName==="+fileName);
// 写入文件,暂定文件名为a.txt,可以从fileName中提取文件名:
//fi.write(new File(uploadPath + fileName));
InputStream is=fi.getInputStream();
System.out.println(insert(is,(int)fi.getSize()));
}
}
}
catch(Exception e) {
// 可以跳转出错页面
}
}
public String getFileName(String path){
int x=path.lastIndexOf("\\");
int y=path.lastIndexOf("/");
String fileName="";
if(x>y){
fileName= path.substring(path.lastIndexOf("\\")+1,path.length());
}else{
fileName=path.substring(path.lastIndexOf("/")+1,path.length());
}
return fileName;
}
public int insert(InputStream is,int size){
Connection con=DBConnection.getConnection();
PreparedStatement pstm=null;
String sql="insert into testblob values(?,?)";
int n=-1;
try {
pstm=con.prepareStatement(sql);
pstm.setInt(1,1);
pstm.setBinaryStream(2,is,size);
n=pstm.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
pstm.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return n;
}