upload.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312">
<title>上傳文件</title>
</head>
<body>
<form name="upload" action="upload.jsp" enctype="multipart/form-data" method="post">
用戶名:<input type="text" name="UserName" value="" size="15"/><br>
口令:<input type="password" name="Password" value="" size="15"/><br>
選擇上傳文件<input type="file" name="FileName" value="" size="30"/><br>
<input type="submit" value="提交"/>
</form>
</body>
</html>
html代碼如上,其中 charset=GB2312,當爲UTF-8時不能成功讀取中文名字的txt文件名,但內容可以正常讀取。有文件上傳操作
所以 enctype採用multipart/form-data。方式。不寫的情況下默認是application/x-www-form-urlencoded
下面爲JSP代碼
<%@page import="java.io.FileWriter"%>
<%@page import="java.io.BufferedWriter"%>
<%@page import="java.io.FileReader"%>
<%@page import="java.io.FileOutputStream"%>
<%@ page language="java" contentType="text/html; charset=gb2312"
pageEncoding="gb2312"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>你上傳的內容如下</title>
</head>
<body>
<%request.setCharacterEncoding("gb2312"); %>
<%
ServletInputStream datain=request.getInputStream();
String file="E://javaEE//chapter03//uploaddata.txt";
FileWriter data = new FileWriter(file);
BufferedWriter dataout = new BufferedWriter(data);
int n=datain.read();
byte []b=new byte[200];
String s;
int len;
while((len=datain.readLine(b, 0, 200))!=-1)
{
s=new String(b,0,len);
dataout.write(s);
out.print(s);
out.print("<br>");
}
dataout.flush();
datain.close();
dataout.close();
out.println("上傳成功");
%>
</body>
</html>
先通過流獲取客戶端的發來的數據ServletInputStream 流類型 利用readline操作,將一行保留到byte數組中,再有byte數組轉換成String類型,再利用BufferedWriter
寫入字符串,哈哈,自己想到的方法哦。編碼格式爲UTF-8 和 gb2312都能成功讀取中文。但前提是txt文件需要是ansi格式。