Jsp 上传文件

 
<%
try{
   String temp=(String)session.getId();
   File f1=new File((String)request.getRealPath("photo")+"/",temp);//
f1对象指向上传文件的所在路径
   out.println(f1);
   FileOutputStream o=new FileOutputStream(f1);//文件输出流指向上传文件所在路径
   out.println(o);
   InputStream in=request.getInputStream();//
得到客户端所提交的数据
   byte b[]=new byte[10000000];
   int n;
   while((n=in.read(b))!=-1){
    o.write(b,0,n);
   }
   o.close();
   in.close();
  
//读取临时文件f1,从中获取上传文件的名字和上传文件的内容。
   RandomAccessFile random=new RandomAccessFile(f1,"r");//r代表只读
   int second=1;
   String secondLine=null;
   while(second<=2){
    secondLine=random.readLine();
    second++;
   }
   int position=secondLine.lastIndexOf('//');
   String fileName=new String((secondLine.substring(position+1,secondLine.length()-1)).getBytes("iso-8859-1"), "GB2312");
  
   random.seek(0);/
/重新定位使文件指针指到文件头
   long forthEnPosition=0;
   int forth=1;
   while((n=random.readByte())!=1&&(forth<=4)){
//取到第四行回车符号所在位置,这是上传文件的开始位置
    if((n=='/n')){
     forthEnPosition=random.getFilePointer();
     forth++;
    }
   }
   File f2=new File((String)request.getRealPath("photo")+"/",fileName);
   session.setAttribute("Name",fileName);//将文件保存入SESSION
   RandomAccessFile random2=new RandomAccessFile(f2,"rw");
   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++;
    }
   }
   random.seek(forthEnPosition);
   long startPoint=random.getFilePointer();
   while(startPoint<endPosition-1){
//从上传文件数据开始的位置到数据结算的位置,把数据写入TOMCAT下的PHOTO子目录中,以SESSIONID命名
    n=random.readByte();
    random2.write(n);
    startPoint=random.getFilePointer();
   }
   random2.close();
   random.close();
   f1.delete();
  
   out.println("<script language='javascript'>alert('上传成功');window.close();opener.form1.Photo.value='../photo/"+fileName+"';</script>");
  
}catch(IOException e){
   out.println("文件上传失败");
}
%>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值