common-fileupload是jakarta项目组开发的一个功能很强大的上传文件组件
下面是个html的上传页面:
现在介绍上传文件到服务器,下面只写出相关代码:
以sql2000为例,表结构如下:
字段名:name filecode
类型: varchar image
数据库插入代码为:PreparedStatement pstmt=conn.prepareStatement("insert into test values(?,?)");
代码如下:
这样就实现了上传文件至数据库
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>");
}
这样就实现了上传文件至数据库
==========================================================================
下面代码是在ORACRE中存储任何文件!!
字段类型为long row,看你是否可以用上!!!
其中中文路径的问题已经解决!
package aaa;
//加入相应的包
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
import java.sql.PreparedStatement;
import java.sql.Connection;
public class in extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GBK";
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Get request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
conn conn=new conn();
//转换字符串的编码格式
request.setCharacterEncoding("GBK");
//conn.Getconnect().
//从上一页面获取相应插入的信息
String XMDM=request.getParameter("XMDM");
String ZLLX=request.getParameter("ZLLX");
String SBRQ=request.getParameter("SBRQ");
String ZLNR=request.getParameter("ZLNR");
//将得到的文件路径转换成为相应的文件格式!
java.io.File file=new java.io.File(ZLNR);
//取得文件的长度!!
long l1=file.length();
int s=(int)l1;
String ZLCD=String.valueOf(s);
//取得文件名及后缀!!
String ZLHZ=file.getName() ;
//将文件转换成为数据流!!
FileInputStream str=new FileInputStream(ZLNR);
// String sql="insert into AAA(A,B) values(?,?)";
String sql="insert into GZ_XGZL(XMDM,ZLLX,ZLMC,SBRQ,ZLNR,ZLCD) values(?,?,?,?,?,?)";
//向数据库读流!!连接数据库插入数据。
try {
PreparedStatement pstmt = conn.Getconnect().prepareStatement(sql);
pstmt.setString(1,XMDM);
pstmt.setString(2,ZLLX);
pstmt.setString(3,ZLHZ);
pstmt.setString(4,SBRQ);
pstmt.setBinaryStream(5,str,s);
pstmt.setString(6,ZLCD);
pstmt.execute();
}
catch (SQLException ex) {
}
response.sendRedirect("update.jsp");
}}
===========================================
下面这个适用初学者
<%@ page contentType="text/html; charset=gb2312"%>
<%@ include file="/DataIni/DataOpen.jsp"%>
<%@ include file="/ScriptLib/Init.jsp"%>
<%
int iTotalByte,iTotalRead,iReadByte;
iTotalByte=request.getContentLength();
iTotalRead=0;
iReadByte=0;
byte[] Buffer=new byte[iTotalByte];
if(iTotalByte>0)
{
for(;iTotalRead<iTotalByte;iTotalRead+=iReadByte)
{
try
{
iReadByte=request.getInputStream().read(Buffer,iTotalRead,iTotalByte-iTotalRead);
}
catch(Exception e)
{
e.printStackTrace();
}
}
String strContentType=request.getContentType();
//数据处理开始
String strBuffer=new String(Buffer);
%><!--<br>表单数据:<br>strBuffer<br>--><%
String strBoundary="--"+strContentType.substring(strContentType.lastIndexOf("=")+1,strContentType.length());
String strArray[]=strBuffer.split(strBoundary);
String strSubString;
int iBegin,iEnd;
iBegin=0;iEnd=0;
String strFieldName="";
String strFieldValue="";
String strFilePath="";
String strFileName="";
String strFileType="";
boolean bTrue;
bTrue=false;
int iLocation=0;
for(int iIndex=1;iIndex<strArray.length-1;iIndex++)
{
strSubString=strArray[iIndex];
iBegin=strSubString.indexOf("name=\"",0);
if(iBegin!=-1)
{
strFieldName="";strFieldValue="";
strFilePath="";strFileName="";strFileType="";
iEnd=strSubString.indexOf("\"",iBegin+6);
strFieldName=strSubString.substring(iBegin+6,iEnd);
iBegin=strSubString.indexOf("filename=\"",0); if(iBegin!=-1)
{
bTrue=true;
}
iEnd=strSubString.indexOf("\r\n\r\n",0);
if(bTrue==true)
{
//文件路径
strFilePath=strSubString.substring(iBegin+10,strSubString.indexOf("\"",iBegin+10));strFileName=strFilePath.substring(strFilePath.lastIndexOf("\\")+1);
strFileType=strSubString.substring(strSubString.indexOf("Content-Type: ")+14,strSubString.indexOf("\r\n\r\n"));
%><!--<br>文件类型:<br>strFileType<br>--><%
//文件数据
iBegin=strSubString.indexOf("\r\n\r\n",iBegin);
strFieldValue=strSubString.substring(iBegin+4);
strFieldValue=strFieldValue.substring(0,strFieldValue.lastIndexOf("\n")-1);
%><!--<br>文件路径:<br>strFilePath<br>文件名称:<br>strFileName<br>--><%
byte[] pFile=strFieldValue.getBytes();
byte[] pFileExtend=new byte[pFile.length];
iLocation=strBuffer.indexOf("filename=\"",iLocation);
for(int kIndex=iLocation;kIndex<iTotalByte-2;kIndex++)
{
if(Buffer[kIndex]==13&&Buffer[kIndex+2]==13)
{iLocation=kIndex+4;break;}
}
for(int nIndex=0;nIndex<pFile.length;nIndex++)
{
pFileExtend[nIndex]=Buffer[iLocation+nIndex];
}
/*
//保存到Local Disk;
FileOutputStream pFileOutputStream=new FileOutputStream("F:\\Site_ColligateStatistic\\UploadFile\\"+strFileName);
pFileOutputStream.write(pFileExtend);
pFileOutputStream.close();
*/
session.putValue(strFieldName+"_FileType",strFileType);
session.putValue(strFieldName+"_FilePath",strFilePath);
session.putValue(strFieldName+"_FileName",strFileName);
session.putValue(strFieldName,pFileExtend);
}
else
{
strFieldValue=strSubString.substring(iEnd+4);
strFieldValue=strFieldValue.substring(0,strFieldValue.lastIndexOf("\n")-1);
session.putValue(strFieldName,strFieldValue);
}
bTrue=false;
}
%><!--<br>表单域名:<br>strFieldName<br>表单域值:<br>strFieldValue<br>--><%
}
//数据处理结束
String TypeValue,Id,ItemID;
TypeValue=(String)session.getValue("TypeValue");
ItemID=(String)session.getValue("ItemId");
%><br><%=TypeValue%><br><%=ItemID%><br><%
if(TypeValue!=null)
{
int iDoAction;
iDoAction=0;
if(TypeValue.indexOf("Add",0)!=-1)
{iDoAction=1;}
if(TypeValue.indexOf("Modify")!=-1)
{iDoAction=2;}
if(TypeValue.indexOf("Del")!=-1)
{iDoAction=3;}
odbcQuery="";
Id=(String)session.getValue("RecordId");
switch(iDoAction)
{
case 1:
odbcStmt.executeUpdate("insert into GeneralSystem(ItemID,Category,Subject,Body,History,Type) values('"+ItemID+"','"+(String)session.getValue("Category")+"','"+(String)session.getValue("Subject")+"','"+(String)session.getValue("Body")+"',Now(),'"+(String)session.getValue("OLEFile_FileType")+"')");
odbcRs=odbcStmtUpdate.executeQuery("select top 1 * from GeneralSystem order by ID desc");
if(odbcRs.next())
{
byte[] OLEFile=(byte[])session.getValue("OLEFile");
odbcRs.updateBinaryStream("OLEFile",new ByteArrayInputStream(OLEFile),OLEFile.length);
odbcRs.updateRow();
odbcRs.close();
response.sendRedirect("/System/GeneralSystem/List.jsp");
}
break;
case 2:
response.sendRedirect("/System/GeneralSystem/List.jsp");
break;
case 3:
odbcStmt.executeUpdate("delete from GeneralSystem where ID="+Id);
response.sendRedirect("/System/GeneralSystem/List.jsp");
break;
}
}
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<title></title>
<link rel="stylesheet" type="text/css" href="/StyleLib/Default_Style_Sheet.css">
</head>
<body οnlοad="window.alert('动作失败,系统取消操作!');window.location.href='/System/GeneralSystem/List.jsp';">
<%@ include file="/TemplateLib/Head.jsp"%>
<%@ include file="/TemplateLib/Tail.jsp"%>
<%@ include file="/DataIni/DataClose.jsp"%>
</body>
</html>
=====================================================================
JSP文件上传代码
UploadFileExample1.jsp
view plaincopy to clipboardprint?
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form name="form1" method="post" action="AcceptUploadFile.jsp" enctype="multipart/form-data">
upload file:
<label>
<input type="file" name="upfile" size="50" />
</label>
<p>
<label>
<input type="submit" name="Submit" value="提交" />
</label>
</p>
</form>
<script type='text/javascript'>
//<![CDATA[
document.getElementById('processtime').innerHTML="<span style='font-size: 8pt; font-family: Georgia;'>Run in 158 ms, 10 Queries, Gzip enabled.</span>";
//]]>
</script></body>
</html>
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form name="form1" method="post" action="AcceptUploadFile.jsp" enctype="multipart/form-data">
upload file:
<label>
<input type="file" name="upfile" size="50" />
</label>
<p>
<label>
<input type="submit" name="Submit" value="提交" />
</label>
</p>
</form>
<script type='text/javascript'>
//<![CDATA[
document.getElementById('processtime').innerHTML="<span style='font-size: 8pt; font-family: Georgia;'>Run in 158 ms, 10 Queries, Gzip enabled.</span>";
//]]>
</script></body>
</html>
AccepteUploadFile.jsp
view plaincopy to clipboardprint?
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<%@ page import="java.io.*"%>
<%!
public String codeToString(String str)
{
String s=str;
try
{
byte tempB[]=s.getBytes("ISO-8859-1");
s=new String(tempB);
return s;
}
catch(Exception e)
{
return s;
}
}
%>
<%
String tempFileName=new String("tempFileName1");//接收上传的文件内容的临时文件的文件名
File tempFile1=new File("D:/",tempFileName);
FileOutputStream outputFile1=new FileOutputStream(tempFile1);
InputStream fileSource1=request.getInputStream();//得到客户端提交的所有数据
byte b[]=new byte[1000];
int n;
while((n=fileSource1.read(b))!=-1)
{
outputFile1.write(b,0,n); //将得到的客户端数据写入临时文件
}
outputFile1.close();
fileSource1.close();
RandomAccessFile randomFile1=new RandomAccessFile(tempFile1,"r");
randomFile1.readLine();//读取第一行数据
String FilePath=randomFile1.readLine();//读取第二行数据,这行数据包括了文件的路径和文件名
int position=FilePath.lastIndexOf('\\'); //等到文件名
String filename=codeToString(FilePath.substring(position+1,FilePath.length()-1));
randomFile1.seek(0);//重新定位指针到文件头
long forthEnterPosition=0;
int forth=1; //得到第4行回车符号的位置,这是上传文件的开始位置
while((n=randomFile1.readByte())!=-1&&(forth<=4))
if(n=='\n')
{
forthEnterPosition=randomFile1.getFilePointer();
forth++;
}
File FileUploadDir=new File("C:/Tomcat5/webapps/ROOT/file/","upload");
FileUploadDir.mkdir(); //生成上传文件的目录
File saveFile1=new File("C:/Tomcat5/webapps/ROOT/file/upload/",filename);
RandomAccessFile randomFile2=new RandomAccessFile(saveFile1,"rw");
randomFile1.seek(randomFile1.length());
long endPosition=randomFile1.getFilePointer();//找到上传的文件数据的结束位置,即倒数第4行
int j=1;
while((endPosition>=0)&&(j<=4))
{
endPosition--;
randomFile1.seek(endPosition);
if(randomFile1.readByte()=='\n')
j++;
}
randomFile1.seek(forthEnterPosition);
long startPoint=randomFile1.getFilePointer();
while(startPoint<endPosition-1)
{
randomFile2.write(randomFile1.readByte());
startPoint=randomFile1.getFilePointer();
}
randomFile2.close();
randomFile1.close();
tempFile1.delete();
out.print("file:"+filename+" succeed upload!<br/>");
%>
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<%@ page import="java.io.*"%>
<%!
public String codeToString(String str)
{
String s=str;
try
{
byte tempB[]=s.getBytes("ISO-8859-1");
s=new String(tempB);
return s;
}
catch(Exception e)
{
return s;
}
}
%>
<%
String tempFileName=new String("tempFileName1");//接收上传的文件内容的临时文件的文件名
File tempFile1=new File("D:/",tempFileName);
FileOutputStream outputFile1=new FileOutputStream(tempFile1);
InputStream fileSource1=request.getInputStream();//得到客户端提交的所有数据
byte b[]=new byte[1000];
int n;
while((n=fileSource1.read(b))!=-1)
{
outputFile1.write(b,0,n); //将得到的客户端数据写入临时文件
}
outputFile1.close();
fileSource1.close();
RandomAccessFile randomFile1=new RandomAccessFile(tempFile1,"r");
randomFile1.readLine();//读取第一行数据
String FilePath=randomFile1.readLine();//读取第二行数据,这行数据包括了文件的路径和文件名
int position=FilePath.lastIndexOf('\\'); //等到文件名
String filename=codeToString(FilePath.substring(position+1,FilePath.length()-1));
randomFile1.seek(0);//重新定位指针到文件头
long forthEnterPosition=0;
int forth=1; //得到第4行回车符号的位置,这是上传文件的开始位置
while((n=randomFile1.readByte())!=-1&&(forth<=4))
if(n=='\n')
{
forthEnterPosition=randomFile1.getFilePointer();
forth++;
}
File FileUploadDir=new File("C:/Tomcat5/webapps/ROOT/file/","upload");
FileUploadDir.mkdir(); //生成上传文件的目录
File saveFile1=new File("C:/Tomcat5/webapps/ROOT/file/upload/",filename);
RandomAccessFile randomFile2=new RandomAccessFile(saveFile1,"rw");
randomFile1.seek(randomFile1.length());
long endPosition=randomFile1.getFilePointer();//找到上传的文件数据的结束位置,即倒数第4行
int j=1;
while((endPosition>=0)&&(j<=4))
{
endPosition--;
randomFile1.seek(endPosition);
if(randomFile1.readByte()=='\n')
j++;
}
randomFile1.seek(forthEnterPosition);
long startPoint=randomFile1.getFilePointer();
while(startPoint<endPosition-1)
{
randomFile2.write(randomFile1.readByte());
startPoint=randomFile1.getFilePointer();
}
randomFile2.close();
randomFile1.close();
tempFile1.delete();
out.print("file:"+filename+" succeed upload!<br/>");
%>