第一个文件 <FORM METHOD="POST" ACTION="update_bl.jsp" ENCTYPE="multipart/form-data"> <td> <BR><BR> <INPUT TYPE="FILE" NAME="FILE1" SIZE="50"><BR> <INPUT TYPE="SUBMIT" VALUE="上传"> </td> </FORM> 第二个文件 <HTML> <BODY BGCOLOR="white"> <% // Connect to the database Class.forName("org.gjt.mm.mysql.Driver").newInstance(); Connection con = DriverManager.getConnection("jdbc:mysql://localhost/fzzs?user=root&password=&useUnicode=true&characterEncoding=8859_1"); // SQL Request Statement stmt = con.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery("insert into bl(tp) values('')"); rs = stmt.executeQuery("select id, tp from bl order by id desc");
// if the resultset is not null if (rs.next()){ // Initialization mySmartUpload.initialize(pageContext); // Upload mySmartUpload.upload(); // upload file in the DB if this file is not missing if (!mySmartUpload.getFiles().getFile(0).isMissing()){ try { rs.updateString("tp",mySmartUpload.getFiles().getFile(0).getFileName()); // Add the current file in the DB field mySmartUpload.getFiles().getFile(0).fileToField(rs,"tp"); // Update rs.updateRow(); } catch(Exception e) { out.println("An error occurs : " + e.toString()); } } } // Display the number of files uploaded out.println("1 file(s) uploaded in the database."); rs.close(); stmt.close(); con.close(); %> </BODY> </HTML>
<FORM METHOD="POST" ACTION="update_bl.jsp" ENCTYPE="multipart/form-data">
<td>
<BR><BR>
<INPUT TYPE="FILE" NAME="FILE1" SIZE="50"><BR>
<INPUT TYPE="SUBMIT" VALUE="上传">
</td>
</FORM>
第二个文件
<HTML>
<BODY BGCOLOR="white">
<%
// Connect to the database
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/fzzs?user=root&password=&useUnicode=true&characterEncoding=8859_1"); // SQL Request
Statement stmt = con.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("insert into bl(tp) values('')");
rs = stmt.executeQuery("select id, tp from bl order by id desc");
// if the resultset is not null
if (rs.next()){ // Initialization
mySmartUpload.initialize(pageContext); // Upload
mySmartUpload.upload(); // upload file in the DB if this file is not missing
if (!mySmartUpload.getFiles().getFile(0).isMissing()){ try {
rs.updateString("tp",mySmartUpload.getFiles().getFile(0).getFileName());
// Add the current file in the DB field
mySmartUpload.getFiles().getFile(0).fileToField(rs,"tp"); // Update
rs.updateRow();
} catch(Exception e) {
out.println("An error occurs : " + e.toString());
}
}
} // Display the number of files uploaded
out.println("1 file(s) uploaded in the database.");
rs.close();
stmt.close();
con.close();
%>
</BODY>
</HTML>
<%
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_App\\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)session.getValue("表单域名")返回表单域值,而(byte[])session.getValue("File上传控件域名")返回的字节数组就可以用new ByteArrayInputStream(byte[])调用updateBinaryStream来更新到数据库了
1。blob 的内容有多打!(oracle的某些工具包不能传输超过某个大小的内容)
2。blob的存取都比较费时间,还是存为本地文件,在数据库中放uri的好
文件上传BEAN
* */package com.xw.util;import java.io.*;
import javax.servlet.*;
import javax.servlet.jsp.*;import com.jspsmart.upload.*;public class FileUpload {
PageContext pc; //JSP环境 int TotalMaxFileSize; //附件大小
public String savePath; //附件存储路径
public int size;
String spe = java.io.File.separator;
String uploadIf = null; public FileUpload() {
} public void upload(PageContext pc) {
// 新建一个SmartUpload对象 try {
SmartUpload su = new SmartUpload();
su.initialize(pc);
su.setTotalMaxFileSize(TotalMaxFileSize);
int count = su.save(getSavePath() + spe);
su.upload();
com.jspsmart.upload.File file = su.getFiles().getFile(0);
// 若文件不存在则继续
if (file.isMissing()) {
uploadIf = "文件上传失败,请重新上传!"; return;
}
else {
// 显示当前文件信息
java.io.File fileDir = new java.io.File(getSavePath());
java.io.File upfiles[] = fileDir.listFiles();
int cont = upfiles.length;
if (cont != 0) { //当前用户目录中有文件
for (int i = 0; i < cont; i++) { if (upfiles[i].getName().equals(file.getFileName())) {
//System.out.println("3");
uploadIf = "请不要传送相同名字的文件!";
//uploadIf="don't upload the same file";
return;
}
else {
// 将文件另存
//file.saveAs("/upload/" + file.getFileName());
//另存到以WEB应用程序的根目录为文件根目录的目录下
//file.saveAs(getSavePath()+ file.getFileName(),su.SAVE_VIRTUAL);
file.saveAs(getSavePath() + spe + file.getFileName(),
su.SAVE_PHYSICAL); uploadIf = "文件上传成功!";
//uploadIf = "upload succed!";
//另存到操作系统的根目录为文件根目录的目录下
//file.saveAs("c:\\temp\\" + myFile.getFileName(),su.SAVE_PHYSICAL);
}
}
}
else { //当前用户目录中无文件
file.saveAs(getSavePath() + spe + file.getFileName(),
su.SAVE_PHYSICAL); uploadIf = "文件上传成功!"; }
} }
catch (ServletException se) {
System.out.print(se.toString());
}
catch (SmartUploadException sue) {
System.out.print(sue.toString());
}
catch (IOException io) {
System.out.print(io.toString());
}
} public String getSavePath() {
return savePath;
}//文件保存路径
public void setSavePath(String userName) {
java.io.File file = new java.io.File(spe + "upload" + spe + userName);
if (!file.isDirectory()) {
file.mkdirs();
}
String str = file.getAbsolutePath();
this.savePath = str;
}
//获得用户设置的附件大小
public int getSize() {
return size;
}
//设置附件大小
public void setSize(int size) {
this.size = size;
}
//删除已上传的的文件
public void delFile(String fileName) {
java.io.File fileDir = new java.io.File(getSavePath());
java.io.File[] files = fileDir.listFiles();
int count = files.length;
for(int i = 0; i< count;i++){
if(fileName.equals(files[i].getName())){
java.io.File afile = new java.io.File(getSavePath()+files[i].getName());
afile.delete();
return;
}
} } public PageContext getRs() {
return pc;
} public void setPc(PageContext pc) {
this.pc = pc;
}//邮件最大容量
public void setTotalMaxFileSize(int TotalMaxFileSize) {
this.TotalMaxFileSize = TotalMaxFileSize;
} public int getTotalMaxFileSize() {
return TotalMaxFileSize;
} //返回上传成功与否信息
public String getUploadIf() {
return uploadIf;
}//测试
public static void main(String[] args) {
String username = "test2";
FileUpload fu = new FileUpload();
fu.setSavePath(username);
System.out.println(fu.getSavePath());
}}
mySmartUpload.setTotalMaxFileSize(6000000);
//mySmartUpload.setAllowedFilesList("txt,doc,xls,jpg,gif"); mySmartUpload.upload();
for (int i=0;i<mySmartUpload.getFiles().getCount();i++)
{
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(i);
if (!myFile.isMissing())
{
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("OracleDS");
Conn = ds.getConnection();
medianame=myFile.getFileName();
exname=myFile.getFileExt();
size1=myFile.getSize();
TypeMIME=myFile.getTypeMIME();
SubTypeMIME=myFile.getSubTypeMIME();
FilePathName=myFile.getFilePathName();
Statement aStmt = Conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
Rs = aStmt.executeQuery("SELECT MC,NR,DX,MIME,EXT FROM TEST");
Rs.moveToInsertRow();
Rs.updateString("MC",medianame);
Rs.updateInt("DX",size1);
Rs.updateString("MIME",TypeMIME);
Rs.updateString("EXT",exname);
byte buf[] = new byte[myFile.getSize()];
for (int j=0;j<myFile.getSize();j++)
{
//out.println(myFile.getBinaryData(j));
buf[j]=myFile.getBinaryData(j);
}
//File file1 = new File(FilePathName);
//FileInputStream fis = new FileInputStream(file1);
//InputStream is = fis;
//Rs.updateBinaryStream("NR",is,new Long(file1.length()).intValue()); myFile.fileToField(Rs,"NR");
//ByteArrayInputStream bas = new ByteArrayInputStream(buf);
//Rs.updateBytes("NR",buf);
Rs.insertRow();
Rs.moveToCurrentRow();
Rs.close();
Conn.close();
out.println("FieldName = " + medianame + "<BR>");
out.println("Size = " + myFile.getSize() + "<BR>");
out.println("FileExt = " + myFile.getFileExt() + "<BR>");
out.println("FilePathName = " + myFile.getFilePathName() + "<BR>");
out.println("ContentType = " + myFile.getContentType() + "<BR>");
out.println("ContentDisp = " + myFile.getContentDisp() + "<BR>");
out.println("TypeMIME = " + myFile.getTypeMIME() + "<BR>");
out.println("SubTypeMIME = " + myFile.getSubTypeMIME() + "<BR>");
break;
}
}
设置一下就行了