使用到页面上传下载功能,学习其大致原理。
保存文件时要注意保存时的命名!
粗略实现如下:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("服务器路径:"+getServerPath());
//创建输出流,用来输出读取的文件
OutputStream out = null;//new FileOutputStream("");
//通过request获取前台的二进制输入流
ServletInputStream in = request.getInputStream();
//定义表单域的分隔符
String startSp = "";
String endSp = "";
//读出流中的数据,并且
//创建缓冲区
byte [] buff = new byte[128];
int i = -1;//存储每次读取的数据的长度
//读取分隔符
i = in.readLine(buff, 0, 128);
startSp = new String(buff,0,i);
endSp = startSp.replace("\r\n", "")+"--\r\n";
System.out.println("分隔符:"+startSp);
//第一行读取完毕
//循环读取表单域
while((i=in.readLine(buff, 0, 128))!=-1){
String str = new String(buff,0,i);
int nameIndex = -1;
if((nameIndex = str.indexOf("name=\""))!=-1){
nameIndex+=6;
//取出表单域的name
String name = str.substring(nameIndex, str.indexOf("\"",nameIndex));
int fileNameIndex = -1;
if((fileNameIndex=str.indexOf("filename=\""))!=-1){
System.out.println("文件域开始:");
//取出文件名
String fileName = str.substring(fileNameIndex+10, str.indexOf("\"",fileNameIndex+10));
System.out.println("name:"+name);
System.out.println("文件名:"+fileName);
//获取服务器路径
String path = getServerPath();
//初始化输出流
out = new FileOutputStream(path+fileName);
//读取文件类型
i = in.readLine(buff, 0, 128);
str = new String(buff, 0, i);
String fileType = str.substring(str.indexOf(":")+1);
System.out.println("文件类型:"+fileType);
//读取空行
in.readLine(buff, 0, 128);
//开始读取文件内容
System.out.println("文件内容:");
while((i=in.readLine(buff, 0, 128))!=-1){
str = new String(buff, 0, i);
if(str.equals(endSp) || str.equals(startSp)){
break;
}else{
out.write(buff,0,i);
System.out.print(str);
}
}
}else{
//读空行
in.readLine(buff, 0, 128);
//读取表单域的值
i=in.readLine(buff, 0, 128);
String value = new String(buff,0,i);
//value = new String(value.getBytes("iso8859-1"),"utf-8");
System.out.println(name+":"+value);
}
}
//System.out.print(str);
}
in.close();
out.close();
}
//获取服务器路径
private String getServerPath(){
String path = "";
path = this.getServletContext().getRealPath("/");
return path;
}