文件的文件上传下载代码,感激不尽!
struts ,mvc,JSP都可以!
<%@ page contentType="text/html;charset=gb2312" import="java.io.*" %>
<%! public String codeToString(String str)
{
String s=str;
try{
byte tempB[]=s.getBytes("ISO-8859-1");
s=new String(tempB);
return s;
}
catch(Exception e){return s;}
} %>
<html>
<body>
<%try{
String tempFileName=new String("tempFileName1");
File tempFile=new File("D:/",tempFileName);
FileOutputStream output=new FileOutputStream(tempFile);
InputStream in=request.getInputStream();
byte b[]=new byte[1000];
int n;
while((n=in.read(b))!=-1)
output.write(b,0,n);
output.close();
in.close();
RandomAccessFile randomFile1=new RandomAccessFile(tempFile,"r");
randomFile1.readLine();
String FilePath=randomFile1.readLine();
int Position=FilePath.lastIndexOf('\\');
String FileName=codeToString(FilePath.substring(Position+1,FilePath.length()-1));
randomFile1.seek(0);
long forthEnterPosition=0;
int forth=1;
while((n=randomFile1.readByte())!=-1&&forth<=4)
if(n=='\n')
{forthEnterPosition=randomFile1.getFilePointer();
forth++;}
File uploadDir=new File("D:/","upload");
uploadDir.mkdir();
File saveFile=new File("D:/upload/",FileName);
RandomAccessFile randomFile2=new RandomAccessFile(saveFile,"rw");
randomFile1.seek(randomFile1.length());
long endPosition=randomFile1.getFilePointer();
int j=1;
while((endPosition>=0)&&j<=4)
{
endPosition--;
randomFile1.seek(endPosition);
if(randomFile1.readByte()=='\n')
j++;
}
randomFile1.seek(forthEnterPosition);
long startPoint=randomFile1.getFilePointer();
while(startPoint<endPosition-1)
{
randomFile2.write(randomFile1.readByte());
startPoint=randomFile1.getFilePointer();
}
randomFile2.close();
randomFile1.close();
out.print("文件"+FileName+"上传成功!");
}
catch(Exception e)
{e.printStackTrace();}
%>
</body>
</html>