问题描述:

HTML

 <form enctype="multipart/form-data" method="post" action="addCompany">

<fieldset>

<legend>Add Company</legend>

<br/>

<label>Company Name:</label>

<input name="name" size="30" type="text"/>

<br/>

<label>Company Logo:</label>

<input name="file" size="30" type="file"/>

<br/>

<span id="updateError" class="errorMessage"></span>

<button type="submit" class="jUiButton">Submit</button>

</fieldset>

</form>

<script>$(".jUiButton").button()</script>

Java Servlet

// Check that we have a file upload request

boolean isMultipart = ServletFileUpload.isMultipartContent(request);

if(isMultipart && request.getContentType() != null)

{

// Create a factory for disk-based file items

FileItemFactory factory = new DiskFileItemFactory();

// Create a new file upload handler

ServletFileUpload upload = new ServletFileUpload(factory);

// Parse the request

List /* FileItem */ items = null;

try

{

items = upload.parseRequest(request);

}

catch(FileUploadException e) {}

// Process the uploaded items

Iterator iter = items.iterator();

FileItem cvFile = null;

while(iter.hasNext())

{

FileItem item = (FileItem)iter.next();

if(item.isFormField())

{

if(item.getFieldName().equals("name"))

name = item.getString();

}

else

{

cvFile = item;

}

if(name != null && cvFile != null)

{

directoryName = request.getRealPath("/") + "/Uploads/Companies/" + name + "/";

File theDir = new File(directoryName);

if (!theDir.exists())

theDir.mkdir();

File uploadedFile = new File(directoryName + cvFile.getName());

try

{

cvFile.write(uploadedFile);

}

catch(Exception e) {}

}

}

I get a null exception here (in the last if statement):

File uploadedFile = new File(directoryName + cvFile.getName());

网友答案:

You have a problem with your code (and I'm not even a Java guy).

FileItem cvFile = null;

You set cvFile to null here.

while(iter.hasNext())
{
   FileItem item = (FileItem)iter.next();

   if(item.isFormField())
   {
     if(item.getFieldName().equals("name"))
        name = item.getString();
   }
   else
   {
      cvFile = item;
   }

If the first branch of the if is take (item.isFormField()), cvFile remains null (its value never changes from where it was initialized).

File uploadedFile = new File(directoryName + cvFile.getName());

You use cvFile.getName() here, but cvFile may still be null.

网友答案:

Where do you set cvFile.name to something, either via setName or otherwise? I think your name is null. I don't see it set on item. I think see cvFile is assigned to an object, but the name object you try access via getName is null.

相关阅读:
Top