日期:2014-05-17 浏览次数:20892 次
第一个文件uploadfile.jsp
<%@ page contentType="text/html;charset=GB2312" language="java" %>
<html>
<head><title>文件上传</title></head>
<body>
<form name="form1" method="post" action="acceptUploadFile.jsp" enctype="multlpart/form-data">
upload:
<label>
<input type="file" name="upfile" size="30"/>
</label>
<p>
<label>
<input type="submit" name="submit" value="提交" />
</label>
</p>
</form>
</body>
</html>
第二个文件 acceptUploadFile.jsp
<%@ page contentType="text/html;charset=GB2312" language="java" %>
<%@ page 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;
}
}%>
<%
//接收上传的文件内容的临时文件的文件名
String tempFileName = new String("tempFileName1");
String path = request.getRealPath("/");
File tempFile1 = new File(path,tempFileName);
FileOutputStream outputFile1 = new FileOutputStream(tempFile1);
//得到客户端提交的所有数据
InputStream fileSource1 = request.getInputStream();
byte b[] = new byte[1000];
int n ;
while((n = fileSource1.read(b)) != -1) {
outputFile1.write(b,0,n); //将得到的客户端数据写入临时文件
}
outputFile1.close();
fileSource1.close();
RandomAccessFile randomFile1 = new RandomAccessFile(tempFile1,"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 FileUploadDir = new File(path,"upload");
FileUploadDir.mkdir(); //生成上传文件的目录
File saveFile1 = new File(path + "/upload", fileName);
RandomAccessFile randomFile2 = new RandomAccessFile(saveFile1,"rw");
randomFile1.seek(randomFile1.length())