JSP文件上传简单实例
1、index.html代码:
<html>
<head>
<title>上传图片</title>
</head>
<body>
<form action="do_upload.jsp" method="post" enctype="multipart/form-data">
<input type="file" name="Photo">
<input type="submit" value="上传">
</form>
</body>
</html>
2、使用到的函数和类说明
File类文件和目录路径名的抽象表示形式,
File(parent,child)方法根据 parent 抽象路径名和 child 路径名字符串创建一个新File实例
FileOutputStream文件输出流,InputStream输入流,将输入数据看成一根管道,可以形象的将输入流比喻成管道的入口,而输出流比喻成管道的出口。
read(byte[] b) 从此输入流中将最多 b.length 个字节的数据读入一个字节数组中。read() 从此输入流中读取一个数据字节。
write(int b) 将指定字节写入此文件输出流,write(byte[] b, int off, int len) 将指定字节数组中从偏移量 off 开始的 len 个字节写入此文件输出流。write(byte[] b) 将 b.length 个字节从指定字节数组写入此文件输出流中
Random.readLine()逐行读入,Random.seek(int pos)设置到此文件开头测量到的文件指针偏移量,该位置发生下一个读取和写入操作,Random.getFilePointer()返回此文件当前偏移量,Random.readByte()此方法从该文件的当前文件指针开始读取第一个字节。
java.lang.String.lastIndexOf(char c)返回最后一次出现的指定字符在此字符串中的索引
3、do_upload.jsp
<%@ page contentType="text/html;charset=gb2312" language="java"%>
<%@ page import="java.io.*"%>
<html>
<head>
<meta http-equiv="content-Type" contentType="text/html;charset=gb2312">
<title>上传</title>
</head>
<body>
<%
try{
String temp=(String)session.getId();//获得sessionId
File f1=new File((String)request.getRealPath("photo")+"/",temp); //获得photo所在的目录,并加上sessionId
out.println(f1);
FileOutputStream o=new FileOutputStream(f1); //文件输出流指向上传文件所在路径
out.println(o);
InputStream in=request.getInputStream(); //从客户端获得文件输入流
int n;
byte b[]=new byte[10000000];//设置缓冲数组的大小
while((n=in.read(b))!=-1){
o.write(b,0,n); //将数据从输入流读入到缓冲数组然后再从缓冲数组写入到文件中
}
o.close();
in.close(); //关闭输入流和文件输出流
RandomAccessFile random=new RandomAccessFile(f1,"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");//去掉临时文件名中的sessionId,获得文件名,并用iso-8859-1编码,
避免出现中文乱码问题
random.seek(0);
long forthEnPosition=0;
int forth=1;
while((n=random.readByte())!=1&&forth<=4){
if(n=='\n'){
forthEnPosition=random.getFilePointer();
forth++;
}//去掉临时文件开头的4个'\n'字符
}
File f2=new File((String)request.getRealPath("photo")+"/",filename);
//以文件的名创建另一个文件随机读取
RandomAccessFile random2=new RandomAccessFile(f2,"rw");
random.seek(random.length());
long endPosition=random.getFilePointer(); //以文件的名创建另一个文件随机读取写入流
int j=1;
long mark=endPosition;
while(mark<=0&&j<=6){ //去掉临时文件末尾的6个'\n'字符
mark--;
random.seek(mark);
n=random.readByte();
if(n=='\n'){
endPosition=random.getFilePointer();
j++;
}
}
random.seek(forthEnPosition);
long startPosition=random.getFilePointer();
while(startPosition<endPosition-1){//将临时文件去掉头尾后写入到新建的文件中
n=random.readByte();
random2.write(n);
startPosition=random.getFilePointer();
}
random2.close();
random.close();
f1.delete();
%>
<script language="javascript">alert("文件上传成功!");history.back();</script>
<%
}catch(Exception e)
{
e.printStackTrace();
out.println("上传文件失败!");
}
%>