jsp核心代码:
<body>
<form name="frm_test" action="${pageContext.request.contextPath }/upload" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="userName"> <br/>
文件: <input type="file" name="file_txt"> <br/>
<input type="submit" value="登录">
</form>
</body>
enctype=”multipart/form-data”在文件上传实力中尤为重要不可缺少
servlet实现对上传文件获取,简单输出文件中的内容:
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1. 获取表单数据流
InputStream in = request.getInputStream();
//2. 转换流
InputStreamReader inStream = new InputStreamReader(in, "UTF-8");
//3. 缓冲流
BufferedReader reader = new BufferedReader(inStream);
// 输出数据
String str = null;
while ((str = reader.readLine()) != null) {
System.out.println(str);
}
// 关闭
reader.close();
inStream.close();
in.close();
}
输出结果:
------WebKitFormBoundaryGoQviatB7iM1dhPr
Content-Disposition: form-data; name="userName"
tom
------WebKitFormBoundaryGoQviatB7iM1dhPr
Content-Disposition: form-data; name="file_txt"; filename="test.txt"
Content-Type: text/plain
test
test
------WebKitFormBoundaryGoQviatB7iM1dhPr--
实现简单的实现,这样主要是应用了字节流去接收文件,在使用转换流把字节流转换成字符流最后存在字符缓冲流中完成输出,注意不要忘记对servlet进行配置