上传文件时的NPE

时间:2015-06-17 14:44:57

标签: java html file servlets upload

我试图允许用户使用HTML表单上传文件。表单输入将由我的Java Servlet doPost方法处理。

我目前正在获取NPE,因为Java无法从POST请求中读回文件。

request.getPart(“file”)返回null而不是文件。任何人都可以解释我在这里出错的地方吗?

由于

HTML表单

<form method="post" action="Serv/FileUpload" id="myForm" enctype="multipart/form-data" >
<input multiple="true" type="file" name="file" label="Select Some Files" id="file" />
<input type="submit" label="Submit" value="Upload attached file"/>

Servlet方法

private void fileUpload( HttpServletRequest request, HttpServletResponse response, Connection connection, PrintWriter out ) throws ServletException,
                                                                                                                           IOException
{

    response.setContentType( "text/html;charset=UTF-8" );

    final String path = "uploads/";
    final Part filePart = request.getPart( "file" );

    System.out.println( "File part " + filePart );

    final String fileName = getFileName( filePart );

    OutputStream outStream = null;
    InputStream filecontent = null;
    final PrintWriter writer = response.getWriter();

    try
    {
        outStream = new FileOutputStream( new File( path + fileName ) );
        filecontent = filePart.getInputStream();

        int read = 0;
        final byte[] bytes = new byte[1024];

        while( (read = filecontent.read( bytes )) != -1 )
        {
            outStream.write( bytes, 0, read );
        }
        out.println( "Successfully uploaded file." );

    }
    catch( FileNotFoundException e )
    {
        out.println( "<br/> ERROR: " + e.getMessage() );

    }
    finally
    {
        if( outStream != null )
        {
            outStream.close();
        }
        if( filecontent != null )
        {
            filecontent.close();
        }
        if( writer != null )
        {
            writer.close();
        }
    }
}

Web.xml中

<web-app 
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<description>TMS</description>
<resource-ref>
<description>Oracle Datasource</description>
<res-ref-name>jdbc/TMS</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>

0 个答案:

没有答案