views:

52

answers:

1

I want to upload files outisde web server like in d d drive into servlets, I but I'm not able to upload them.

What I have to do to make functionality like this enable in Tomcat 6.0?

+2  A: 

This ought just to work. All you basically need to do is to obtain the uploaded file in flavor of an InputStream from the request body. You normally use Apache Commons FileUpload for this. Then you can write it to any OutputStream you like the usual Java IO way, such as FileOutputStream.

Assuming that you're actually using Apache Commons FileUpload which requires Apache Commons IO as a dependency, here's a basic example:

String filename = FilenameUtils.getName(fileItem.getName()); // Important!
File destination = new File("D:/path/to/files", filename);

InputStream input = null;
OutputStream output = null;

try {
    input = fileItem.getInputStream();
    output = new FileOutputStream(destination);
    IOUtils.copy(input, output);
} finally {
    IOUtils.closeQuietly(output);
    IOUtils.closeQuietly(input);
}

Alternatively you can also just use the Fileupload's convenienced FileItem#write() method:

String filename = FilenameUtils.getName(fileItem.getName()); // Important!
File destination = new File("D:/path/to/files", filename);

fileItem.write(destination);

For more examples, hints and tricks, check the FileUpload User Guide and FAQ.

BalusC