JSP文件上传并录入数据库方法之一。在做JSP文件上传时,本来是要用POI处理Excel的,但是在处理过程中出现点问题后来就改用自己编写了,但是Excel格式比较复杂,本人就做了CSV格式的文件上传
1。主要变量有:
String fileName=”"; //记录文件名
String mulu; //记录文件的目录
2。以下就是文件上传的服务器的代码:
public void setupFile(){//上传文件
try{
//use sessionid to create a temp file.
String tempFileName=sessid;
//create the temp file.
File temp=new File(mulu,tempFileName);
FileOutputStream o=new FileOutputStream(temp);
if(len>297){
//write the upload content to the temp file.
InputStream in=newIn;
byte b[]=new byte[1024];
int n;
while((n=in.read(b))!=-1){
o.write(b,0,n);
}
o.close();
in.close();
//read the temp file.
RandomAccessFile random=new RandomAccessFile(temp,”r”);
//read Line2 to find the name of the upload file.
int second=1;
String secondLine=null;
while(second<=2){
secondLine=random.readLine();
second++;
}
//get the last location of the dir char.’//’.
int position=secondLine.lastIndexOf(‘//’);
//get the name of the upload file.
fileName=secondLine.substring(position+1,secondLine.length()-1);
//relocate to the head of file.
random.seek(0);
//get the location of the char.’Enter’ in Line4.
long forthEndPosition=0;
int forth=1;
while((n=random.readByte())!=-1&&(forth<=4)){
if(n==’/n’){
forthEndPosition=random.getFilePointer();
forth++;
}
}
//locate the end position of the content.Count backwards 6 lines.
random.seek(random.length());
long endPosition=random.getFilePointer();
long mark=endPosition;
int j=1;
while((mark>=0)&&(j<=6)){
mark–;
random.seek(mark);
n=random.readByte();
if(n==’/n’){
endPosition=random.getFilePointer();
j++;
}
}
//建立除去表单信息的新文件
File realFile=new File(mulu,fileName);
RandomAccessFile random2=new RandomAccessFile(realFile,”rw”);
//locate to the begin of content.Count for 4 lines’s end position.
random.seek(forthEndPosition);//定位到临时文件第四行的位置
long startPoint=random.getFilePointer();//定位第六行的位置
while(startPoint<endPosition-1){//写文件
n=random.readByte();
random2.write(n);
startPoint=random.getFilePointer();
}
random2.close();//管理随机读写对象
random.close();
temp.delete();//删除临时文件
msgUpfile=”文件读取成功!<br><br>”;
}
else{//没上传文件
msgUpfile=”请上传文件!<br><br>”;
}
}
catch(IOException e){
msgUpfile=”文件上传失败!<br><br>”;
e.printStackTrace();
}
}