处理文件上传时出现java.lang.NullPointerException
如果您能找到我的问题所在以及如何解决它,我将非常感激。 (java.lang.NullPointerException)
这是我的 html,从中我获得一个文本字段,并在此 servlet 中上传 2 个文件
index.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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>File Upload:</h3>
<form action="UploadServlet" method="post"
enctype="multipart/form-data">
<br><br><br><br><br>
Insert your ID (marca) - ex: 101358
<br>
<input type="text" name="rid" size="40" />
<br><br>
Browse your files:
<br>
<input type="file" name="file" size="30" />
<br />
<br/>
<input type="file" name="file" size="30" />
<br />
<br>
<input type="submit" value="Upload File" />
</form>
</body>
</html>
我将上传的文件保存到特定文件夹中,然后进行连接到一个数据库,我想存储从 html 获取的字符串和上传文件的文件路径
UploadServlet.java
public class UploadServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private boolean isMultipart;
private String filePath;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 4 * 1024;
private File file ;
public void init( ){
// Get the file location where it would be stored.
filePath = getServletContext().getInitParameter("file-upload");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart ){
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
//while ( i.hasNext () )
//{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
//String fieldName = fi.getFieldName();
String fileName = fi.getName();
//String contentType = fi.getContentType();
//boolean isInMemory = fi.isInMemory();
//long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( "C:/UploadedFiles/" + fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( "C:/UploadedFiles/" + fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + fileName + " --- saved in C:/UploadedFiles/ " + "<br>");
}
FileItem fi2 = (FileItem)i.next();
if ( !fi2.isFormField () )
{
// Get the uploaded file parameters
//String fieldName2 = fi2.getFieldName();
String fileName2 = fi2.getName();
//String contentType2 = fi2.getContentType();
//boolean isInMemory = fi2.isInMemory();
//long sizeInBytes = fi2.getSize();
// Write the file
if( fileName2.lastIndexOf("\\") >= 0 ){
file = new File( "C:/UploadedFiles/" + fileName2.substring( fileName2.lastIndexOf("\\"))) ;
}else{
file = new File( "C:/UploadedFiles/" + fileName2.substring(fileName2.lastIndexOf("\\")+1)) ;
}
fi2.write( file ) ;
out.println("Uploaded Filename: " + fileName2 + " --- saved in C:/UploadedFiles/ " + "<br>");
}
//}
out.println("</body>");
out.println("</html>");
String idmarca = request.getParameter("rid");
String itemName1 = fi.getName();
String path1 = new String("C:\\UploadedFiles\\" + itemName1.substring(itemName1.lastIndexOf("\\")));
String itemName2 = fi2.getName();
String path2 = new String("C:\\UploadedFiles\\" + itemName2.substring(itemName2.lastIndexOf("\\")));
Connection con = null;
PreparedStatement ps;
try{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:upload";
con = DriverManager.getConnection(db, "", "");
String sql = "INSERT INTO file1(marca,file1,file2) VALUES(?, ?, ?)";
ps = con.prepareStatement(sql);
ps.setString(1, idmarca);
ps.setString(2, path1);
ps.setString(3, path2);
int s = ps.executeUpdate();
if(s>0){
System.out.println("Uploaded successfully !");
}
else{
System.out.println("Error!");
}
}
catch(Exception e){
e.printStackTrace();
}
finally {
// close all the connections.
//ps.close();
//con.close();
}
}catch(Exception ex) {
ex.printStackTrace();
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
throw new ServletException("GET method used with " + getClass( ).getName( )+": POST method required.");
}
}
java.lang.NullPointerException
at UploadServlet.doPost(UploadServlet.java:126)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
I would be very gratefull if you could find where is my problem and how can I fix it. (java.lang.NullPointerException)
here is my html from where I get a textfield and I upload 2 files
index.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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>File Upload:</h3>
<form action="UploadServlet" method="post"
enctype="multipart/form-data">
<br><br><br><br><br>
Insert your ID (marca) - ex: 101358
<br>
<input type="text" name="rid" size="40" />
<br><br>
Browse your files:
<br>
<input type="file" name="file" size="30" />
<br />
<br/>
<input type="file" name="file" size="30" />
<br />
<br>
<input type="submit" value="Upload File" />
</form>
</body>
</html>
in this servlet I save the uploaded files into a specific folder and after that I am connecting to a database where I want to store the string got from html and the file paths from the uploaded files
UploadServlet.java
public class UploadServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private boolean isMultipart;
private String filePath;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 4 * 1024;
private File file ;
public void init( ){
// Get the file location where it would be stored.
filePath = getServletContext().getInitParameter("file-upload");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
if( !isMultipart ){
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
//while ( i.hasNext () )
//{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
//String fieldName = fi.getFieldName();
String fileName = fi.getName();
//String contentType = fi.getContentType();
//boolean isInMemory = fi.isInMemory();
//long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( "C:/UploadedFiles/" + fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( "C:/UploadedFiles/" + fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + fileName + " --- saved in C:/UploadedFiles/ " + "<br>");
}
FileItem fi2 = (FileItem)i.next();
if ( !fi2.isFormField () )
{
// Get the uploaded file parameters
//String fieldName2 = fi2.getFieldName();
String fileName2 = fi2.getName();
//String contentType2 = fi2.getContentType();
//boolean isInMemory = fi2.isInMemory();
//long sizeInBytes = fi2.getSize();
// Write the file
if( fileName2.lastIndexOf("\\") >= 0 ){
file = new File( "C:/UploadedFiles/" + fileName2.substring( fileName2.lastIndexOf("\\"))) ;
}else{
file = new File( "C:/UploadedFiles/" + fileName2.substring(fileName2.lastIndexOf("\\")+1)) ;
}
fi2.write( file ) ;
out.println("Uploaded Filename: " + fileName2 + " --- saved in C:/UploadedFiles/ " + "<br>");
}
//}
out.println("</body>");
out.println("</html>");
String idmarca = request.getParameter("rid");
String itemName1 = fi.getName();
String path1 = new String("C:\\UploadedFiles\\" + itemName1.substring(itemName1.lastIndexOf("\\")));
String itemName2 = fi2.getName();
String path2 = new String("C:\\UploadedFiles\\" + itemName2.substring(itemName2.lastIndexOf("\\")));
Connection con = null;
PreparedStatement ps;
try{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:upload";
con = DriverManager.getConnection(db, "", "");
String sql = "INSERT INTO file1(marca,file1,file2) VALUES(?, ?, ?)";
ps = con.prepareStatement(sql);
ps.setString(1, idmarca);
ps.setString(2, path1);
ps.setString(3, path2);
int s = ps.executeUpdate();
if(s>0){
System.out.println("Uploaded successfully !");
}
else{
System.out.println("Error!");
}
}
catch(Exception e){
e.printStackTrace();
}
finally {
// close all the connections.
//ps.close();
//con.close();
}
}catch(Exception ex) {
ex.printStackTrace();
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
throw new ServletException("GET method used with " + getClass( ).getName( )+": POST method required.");
}
}
java.lang.NullPointerException
at UploadServlet.doPost(UploadServlet.java:126)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当使用
multipart/form-data
请求时,表单数据部分不是通过request.getParameter()
可用作请求参数。它们只能通过request.getPart()
作为表单数据部分使用。但是,当您使用 Apache Commons FileUpload(也许您还没有使用新的 Servlet 3.0 版本,其中getPart()
方法可用)时,那么您实际上应该使用相同的 API 来检索文本字段值。继续迭代
fileItems
。文本字段值就在那里。另请参阅:
When using
multipart/form-data
requests, the form data pars are not available as request parameters byrequest.getParameter()
. They are only available as form data parts byrequest.getPart()
. But as you're using Apache Commons FileUpload (perhaps you aren't using the new Servlet 3.0 version yet wherein thegetPart()
method is available), then you should actually be using the very same API to retrieve the text field value.Continue iterating the
fileItems
. The text field value is in there.See also: