Java: How to upload a file to a WebDAV server from a servlet?

francescoNemesi picture francescoNemesi · Feb 14, 2010 · Viewed 21.9k times · Source

my ajax application uploads a file to a Java application container from the user's browser. What I'd like to do is this: once the uploading has completed I want to "send" the file to a WebDAV server, identified by the host name (i.e. localhost), the port (i.e. 8080) and the location where I want to store the file (i.e. dir1/dir2).

What I am after is basically a WebDAV client framework that enables me to upload a file to WebDAV. In my application I am already using "webdavclient4j", but I don't seem to find a way to upload a file with it?

Any ideas? Thanks in advance for any help you might provide.

F

Answer

Jon Stevens picture Jon Stevens · Feb 17, 2010

You can do it with only a few lines of code using my recently released and super easy to use modern webdav client for java, Sardine. Here is a couple examples (first one uses commons-io to read the file):

Sardine sardine = SardineFactory.begin("username", "password");
byte[] data = FileUtils.readFileToByteArray(new File("/file/on/disk"));
sardine.put("http://yourdavserver.com/adirectory/nameOfFile.jpg", data);

or using streams:

Sardine sardine = SardineFactory.begin("username", "password");
InputStream fis = new FileInputStream(new File("/some/file/on/disk.txt"));
sardine.put("http://yourdavserver.com/adirectory/nameOfFile.jpg", fis);

https://github.com/lookfirst/sardine

cheers,

jon