目前,我正在尝试通过以下代码读取上传文件的内容:
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
String urlConnection = "/DisplayInfo.jsp";
Object htmlFile = request.getParameter("htmlFile");
String contents = "";
File f = (File) htmlFile;
if(f.canRead()) {
Scanner stdin = new Scanner(f);
while(stdin.hasNextLine()) {
contents += stdin.nextLine();
}
stdin.close();
}
//htmlFile = contents;
request.setAttribute("htmlFile1", contents);
getServletContext().getRequestDispatcher(urlConnection).forward(request, response);
}
finally {
out.close();
}
}
定义如下:
</form>
<form action ="MyServlet" method="post">
<input type="file" name="htmlFile">
<input type="submit" value="send">
</form>
,并通过以下方式致电:
</b>
Something here: ${htmlFile1}
</body>
本质上,我正在尝试读取html文件的内容并将其显示在网站正文上。但是,当我尝试解析为字符串contents
时,出现异常,指示该值为空。
是否有更好的方法来做我要尝试的事情?
答案 0 :(得分:0)
request.getParameter("htmlFile");
getParameter()在读取POST请求时始终返回null
您可以通过致电获取请求正文
request.getInputStream()