-2

I just have learned somewhere to upload a file into folder. I followed that tutorial as well and it was working too.

When i give the path C:\MyFile, it's uploading my files.

I'm using a Eclipse IDE, Now i've created a folder inside my project named as files. Unfortunately it's not uploading, you could see a Screenshot that where i've created a folder to upload my files.

SCREENSHOT

enter image description here

and it's not working can you just please help me?

I'm getting an error as:

File not uploaded

Here is my source code of UploadFile.java:

package com.fileupload;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.ha.backend.Sender;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadFile extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private final String UPLOAD_DIRECTORY = "files/";

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // process only if its multipart content
    if (isMultipart) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            // Parse the request
            List<FileItem> multiparts = upload.parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                }
            }
        } 
        catch (Exception e) 
        {
            System.out.println("File not uploaded");
        }
    }
}
}

and here is my index.jsp:

<!DOCTYPE html>
<html>
<head>
<title>Ajax File Upload with Progress Bar</title>
<!-- Include jQuery form & jQuery script file. -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.js" ></script>
<script src="http://malsup.github.com/jquery.form.js" ></script>
<script src="js/fileUploadScript.js" ></script>
<!-- Include css styles here -->
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <h3>Ajax File Upload with Progress Bar</h3>
    <form id="UploadForm" action="UploadFile" method="post"
        enctype="multipart/form-data">
        <input type="file" size="60" id="myfile" name="myfile"> <input
            type="submit" value="Ajax File Upload">

        <div id="progressbox">
            <div id="progressbar"></div>
            <div id="percent">0%</div>
        </div>
        <br />

        <div id="message"></div>
    </form>
</body>
</html>

REMEMBER

When i give the path into UPLOAD_DIRECTORY as C:\Files. then it is working .. But when i create a folder into my eclipse project (See above my screenshot) ..It's saying File not uploaded..

EDITED!!

Now i'm using:

private final String UPLOAD_DIRECTORY =getServletContext().getRealPath("/files/");

But getting error as:

SEVERE: Allocate exception for servlet UploadFile
java.lang.NullPointerException
    at javax.servlet.GenericServlet.getServletContext(GenericServlet.java:125)
    at com.fileupload.UploadFile.<init>(UploadFile.java:20)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:154)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:830)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:137)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:107)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:76)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:934)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:90)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:515)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1012)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:642)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1555)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Surely, Help would be appreciated!!

Tiny
  • 27,221
  • 105
  • 339
  • 599
mohan lal
  • 1
  • 3
  • Is it bad to ask my question here.. – mohan lal Dec 31 '14 at 12:53
  • Can you please help me, I'm still having `Null pointer exception`.. I edited my question please see it.. sir. – mohan lal Dec 31 '14 at 13:04
  • Sir, i edited it ... have a look once sir.. pls.. – mohan lal Dec 31 '14 at 13:05
  • This is the culprit (as in your question), "*Now I've created a folder inside my project named as `files`*". and this is the answer, "*You should not save uploaded files in the deploy folder*" in the accepted answer in the duplicate link. – Tiny Dec 31 '14 at 18:20

1 Answers1

0

Use following code to get real path of your directory:

getServletContext().getRealPath("/files/");

For more information about this method you can see BalusC's answer.

if you are calling this method in init() method, call super.init(config); at first line of your init method (recommended) or using following code:

config.getServletContext().getRealPath("/files/");
Community
  • 1
  • 1
Ali Sepehri.Kh
  • 2,468
  • 2
  • 18
  • 27