下面先介绍上传文件到服务器(多文件上传):import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import org.apache.commons.fileupload.*;
public class upload extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GB2312";
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out=response.getWriter();
try {
DiskFileUpload fu = new DiskFileUpload();
// 设置允许用户上传文件大小,单位:字节,这里设为2m
fu.setSizeMax(2*1024*1024);
// 设置最多只允许在内存中存储的数据,单位:字节
fu.setSizeThreshold(4096);
// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
fu.setRepositoryPath("c:\\windows\\temp");
//开始读取上传信息
List fileItems = fu.parseRequest(request);
// 依次处理每个上传的文件
Iterator iter = fileItems.iterator();//正则匹配,过滤路径取文件名
String regExp=".+\\\\(.+)$";//过滤掉的文件类型
String[] errorType={".exe",".com",".cgi",".asp"};
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem)iter.next();
//忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if((name==null||name.equals("")) && size==0)
continue;
Matcher m = p.matcher(name);
boolean result = m.find();
if (result){
for (int temp=0;temp<errorType.length;temp++){
if (m.group(1).endsWith(errorType[temp])){
throw new IOException(name+": wrong type");
}
}
try{//保存上传的文件到指定的目录//在下文中上传文件至数据库时,将对这里改写
item.write(new File("d:\\" + m.group(1))); out.print(name+" "+size+"<br>");
}
catch(Exception e){
out.println(e);
} }
else
{
throw new IOException("fail to upload");
}
}
}
}
catch (IOException e){
out.println(e);
}
catch (FileUploadException e){
out.println(e);
}
}
}下面是个html的上传页面:<h1>文件上传演示</h1><form name="uploadform" method="POST" action="/upload" ENCTYPE="multipart/form-data"> <table border="1" width="450" cellpadding="4" cellspacing="2" bordercolor="#9BD7FF"> <tr><td width="100%" colspan="2"> 文件1:<input name="x" size="40" type="file"> </td></tr> <tr><td width="100%" colspan="2"> 文件2:<input name="y" size="40" type="file"> </td></tr> <tr><td width="100%" colspan="2"> 文件3:<input name="z" size="40" type="file"> </td></tr> </table> <br/><br/> <table> <tr><td align="center"><input name="upload" type="submit" value="开始上传"/></td></tr> </table></form>现在介绍上传文件到服务器,下面只写出相关代码:以sql2000为例,表结构如下:字段名:name filecode类型: varchar image数据库插入代码为:PreparedStatement pstmt=conn.prepareStatement("insert into test values(?,?)");代码如下: try{
//item.write(new File("d:\\" + m.group(1)));//这段代码如果不去掉,将一同写入到服务器中 int byteread=0; InputStream inStream=item.getInputStream(); //读取输入流,也就是上传的文件内容
pstmt.setString(1,m.group(1));
pstmt.setBinaryStream(2,inStream,(int)size);
pstmt.executeUpdate();
inStream.close(); out.println(name+" "+size+"<br>");
}这样就实现了上传文件至数据库作者:中国论坛网收集 来源:http://www.51one.net
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import org.apache.commons.fileupload.*;
public class upload extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GB2312";
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out=response.getWriter();
try {
DiskFileUpload fu = new DiskFileUpload();
// 设置允许用户上传文件大小,单位:字节,这里设为2m
fu.setSizeMax(2*1024*1024);
// 设置最多只允许在内存中存储的数据,单位:字节
fu.setSizeThreshold(4096);
// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
fu.setRepositoryPath("c:\\windows\\temp");
//开始读取上传信息
List fileItems = fu.parseRequest(request);
// 依次处理每个上传的文件
Iterator iter = fileItems.iterator();//正则匹配,过滤路径取文件名
String regExp=".+\\\\(.+)$";//过滤掉的文件类型
String[] errorType={".exe",".com",".cgi",".asp"};
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem)iter.next();
//忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if((name==null||name.equals("")) && size==0)
continue;
Matcher m = p.matcher(name);
boolean result = m.find();
if (result){
for (int temp=0;temp<errorType.length;temp++){
if (m.group(1).endsWith(errorType[temp])){
throw new IOException(name+": wrong type");
}
}
try{//保存上传的文件到指定的目录//在下文中上传文件至数据库时,将对这里改写
item.write(new File("d:\\" + m.group(1))); out.print(name+" "+size+"<br>");
}
catch(Exception e){
out.println(e);
} }
else
{
throw new IOException("fail to upload");
}
}
}
}
catch (IOException e){
out.println(e);
}
catch (FileUploadException e){
out.println(e);
}
}
}下面是个html的上传页面:<h1>文件上传演示</h1><form name="uploadform" method="POST" action="/upload" ENCTYPE="multipart/form-data"> <table border="1" width="450" cellpadding="4" cellspacing="2" bordercolor="#9BD7FF"> <tr><td width="100%" colspan="2"> 文件1:<input name="x" size="40" type="file"> </td></tr> <tr><td width="100%" colspan="2"> 文件2:<input name="y" size="40" type="file"> </td></tr> <tr><td width="100%" colspan="2"> 文件3:<input name="z" size="40" type="file"> </td></tr> </table> <br/><br/> <table> <tr><td align="center"><input name="upload" type="submit" value="开始上传"/></td></tr> </table></form>现在介绍上传文件到服务器,下面只写出相关代码:以sql2000为例,表结构如下:字段名:name filecode类型: varchar image数据库插入代码为:PreparedStatement pstmt=conn.prepareStatement("insert into test values(?,?)");代码如下: try{
//item.write(new File("d:\\" + m.group(1)));//这段代码如果不去掉,将一同写入到服务器中 int byteread=0; InputStream inStream=item.getInputStream(); //读取输入流,也就是上传的文件内容
pstmt.setString(1,m.group(1));
pstmt.setBinaryStream(2,inStream,(int)size);
pstmt.executeUpdate();
inStream.close(); out.println(name+" "+size+"<br>");
}这样就实现了上传文件至数据库作者:中国论坛网收集 来源:http://www.51one.net
<form name="form1" method="post" ENCTYPE="multipart/form-data" >
<table bgColor="<%=tablebgcolor%>" border="0" cellSpacing="1" width=<%=tablewidth%>>
<!--//在页面上定义隐含参数-->
<input type=hidden name="operate_aspect" value="0" size=20 class=TextWidth>
<input type=hidden name="url" value="<%=hrefUrl%>?ObjectID=<%=studentid%>" size=20 class=TextWidth>
<input type=hidden name="ObjectIDs" size=6 value="<%=studentid%>" class=InputText> <input name="filename" type="file"/></table> <table border="0" width=<%=tablewidth%> height=50 align=center>
<tr>
<td height=25 width="100%" align="center">
<input type=submit value="保存" name=button id=submit onclick="submit_onclick()" style="border-style: ridge" <%=save_displaystat%>>
<!--<input type=reset value="全部重写" name=submit2 style="border-style: ridge"> -->
<input type=button value="返回" onclick="closewin()" name=submit2 style="border-style: ridge">
</td>
</tr></table>
</form> java: com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
String fileName = myFile.getFileName();
if (!myFile.isMissing()) {
}else{
displayinfofun1("文件不存在,请重新选择",url,"","","");
return;
}
System.out.println("大小:"+myFile.getSize());
if(myFile.getSize()>25000){
displayinfofun1("文件只能小于20K,太大会影响网络速度,请重新调整相片的大小",url,"","","");
return;
}
String sql= null;
if(operate_aspect.equals("0")){ //学生
sql="select BK_ZPLJ,BK_Picture from ST_Studentinfo where BK_StudentID="+ ObjectIDs;
}else{
sql="select BK_ZPLJ,BK_ZP from TE_teacherinfo where BK_TeacherID="+ ObjectIDs;
}
rs = DBObjs.ExecuteSQLCanUpdate(sql);
System.out.println("OK3="+sql);
if(rs.next()){ try{ //rs.updateString("BK_ZPLJ",filename);
// Add the current file in the DB field
mySmartUpload.getFiles().getFile(0).fileToField(rs,"BK_Picture");
// Update
rs.updateRow();
DBObjs.freeRS();
rs.close(); } catch(Exception e) {
displayinfofun1("保存失败 ,错误信息:"+e.toString(),url,"","","");
return;
}finally{
DBObjs.freeRS();
if(rs !=null){rs.close();}
} }
if(rs !=null){
DBObjs.freeRS();
rs.close();
}
}catch(Exception e){ //错误提示
displayinfofun1("发生意外错误,请重新启动应用系统 ,错误信息:"+e.toString(),url,"","","");
return;
} displayinfofun("相片成功保存到数据库中",url,"","","",0);
return; }
用stream
郁闷