通过 POST 读取文件内容
Reading file contents via POST
目前我正在尝试通过以下代码读取上传文件的内容:
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
时,我收到一个异常,指示该值为空。
有没有更好的方法来完成我正在尝试的事情?
request.getParameter("htmlFile");
getParameter() 在读取 POST 请求时总是 return null
您可以通过调用
获取请求体
request.getInputStream()
目前我正在尝试通过以下代码读取上传文件的内容:
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
时,我收到一个异常,指示该值为空。
有没有更好的方法来完成我正在尝试的事情?
request.getParameter("htmlFile");
getParameter() 在读取 POST 请求时总是 return null
您可以通过调用
获取请求体request.getInputStream()