JSP程序设计 实验指导
实验步骤
1) 由于编译这个javaBean时需要导入servlet-api.jar包,所以要在环境变量classpath
后面指定这个包的位置,生成class文件之后,jsp文件运行不要这个包。 2) 编写jsp文件运行之,观察上传文件的结果 3) 思考文件重名、文件路径、文件大小等情况
UpFile.java package tom.jiafei; import java.io.*; import java.util.*; import java.util.Date; import javax.servlet.http.*; public class UpFile
{ HttpServletRequest request; HttpSession session; String upFileMessage=\
public void setRequest(HttpServletRequest request) { this.request=request; }
public void setSession(HttpSession session) { this.session=session; }
public String getUpFileMessage()
{ String fileName=null;
try{ String tempFileName=(String)session.getId();//客户的session的id File f1=new File(\ FileOutputStream o=new FileOutputStream(f1); InputStream in=request.getInputStream(); byte b[]=new byte[10000]; int n;
while( (n=in.read(b))!=-1) { o.write(b,0,n); } o.close(); in.close();
RandomAccessFile random=new RandomAccessFile(f1,\ int second=1; //读出f1的第2行,析取出上传文件的名字: String secondLine=null; while(second<=2)
16
JSP程序设计 实验指导
{ secondLine=random.readLine(); second++; }
//获取第2行中目录符号'\\'最后出现的位置 int position=secondLine.indexOf(\ //客户上传的文件的名字是:
fileName=secondLine.substring(position+10,secondLine.length()-1);// if(fileName.indexOf(\
{ position=secondLine.lastIndexOf(\
fileName=secondLine.substring(position+1,secondLine.length()-1);} Calendar calendar=Calendar.getInstance(); calendar.setTime(new Date());
long preName=(calendar.getTimeInMillis()); fileName=preName+fileName;
byte cc[]=fileName.getBytes(\
fileName=new String(cc);//System.out.println(fileName); session.setAttribute(\供show.jsp页面使用 random.seek(0); //再定位到文件f1的开头。 //获取第4行回车符号的位置: long forthEndPosition=0; int forth=1;
while((n=random.readByte())!=-1&&(forth<=4)) { if(n=='\\n')
{ forthEndPosition=random.getFilePointer(); forth++; } }
//根据客户上传文件的名字,将该文件存入磁盘: File f2= new File(\ RandomAccessFile random2=new RandomAccessFile(f2,\
//确定出文件f1中包含客户上传的文件的内容的最后位置,即倒数第6行。 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();
17
JSP程序设计 实验指导
j++; } }
//将random流指向文件f1的第4行结束的位置: random.seek(forthEndPosition); long startPoint=random.getFilePointer();
//从f1读出客户上传的文件存入f2(读取从第4行结束位置和倒数第6行之间的内容)
while(startPoint startPoint=random.getFilePointer(); } random2.close(); random.close(); f1.delete(); //删除临时文件 upFileMessage=fileName;//+\ return upFileMessage; } catch(Exception exp) { if(fileName!=null) { upFileMessage=fileName+\ return upFileMessage; } else { upFileMessage=\ return upFileMessage; } } } } upfile.jsp <%@ page contentType=\<%@ page import=\ 选择要上传的文件: <% upFile.setRequest(request); upFile.setSession(session); %>