views:

42

answers:

1

I want to develope upload and download file from server.

Upload.html

<form action="/UploadFile/UploadFile" method="POST"
enctype="multipart/form-data">Select a file: <input
type="submit" name="button" /> <input type="file" name="first"></form>

UploadFile.servlet

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    String temp = request.getParameter("first");
    System.out.println(temp);
    File origFile = new File(temp);
    FileOutputStream out = new FileOutputStream(request.getContextPath()
            + "pdtImages/" + "FirstFile");
    InputStream ins = new FileInputStream(origFile);
    try {
        System.out.println(request.getContextPath());
        byte[] buf = new byte[1024];
        int len;
        while ((len = ins.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

When I submitted the file I got null pointer error message. I not very familiar with jsp can anybody help me? I want to store the file to the server directory.

+2  A: 

I use Apache commons fileupload for this task.

stacker
I got tried out Apache commons fileupload also i got this java.lang.ClassNotFoundException: org.apache.commons.io.output.DeferredFileOutputStreamerror.
The org.apache.commons.io.output.DeferredFileOutputStream is included in http://commons.apache.org/io/ commons-io you also need to include this in your classpath. (WEB-INF/lib)
stacker
Hi thanks it works.
@newbie123 You should accept answers by clicking the green check mark, otherwise they are listed unanswered.
stacker
Hi can it be done by not using apache.commons?
@newbie123 Basically yes but you would have to implement the parts used from commons by yourself.
stacker