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

前端 未结 2 513
春和景丽
春和景丽 2021-01-02 18:17

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\

相关标签:
2条回答
  • 2021-01-02 18:47

    You can use the Jackrabbit WebDAV Library.

    An example of a WebDAV client to upload content to a WebDAV server (taken from here):

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.URL;
    import org.apache.commons.httpclient.Credentials;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpException;
    import org.apache.commons.httpclient.UsernamePasswordCredentials;
    import org.apache.commons.httpclient.auth.AuthScope;
    import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
    import org.apache.commons.httpclient.methods.RequestEntity;
    import org.apache.jackrabbit.webdav.client.methods.PutMethod;
    
    ...
    
    // WebDAV URL:
    final String baseUrl = ...;
    // Source file to upload:
    File f = ...;
    try{
        HttpClient client = new HttpClient();
        Credentials creds = new UsernamePasswordCredentials("username", "password");
        client.getState().setCredentials(AuthScope.ANY, creds);
    
        PutMethod method = new PutMethod(baseUrl + "/" + f.getName());
        RequestEntity requestEntity = new InputStreamRequestEntity(
            new FileInputStream(f));
        method.setRequestEntity(requestEntity);
        client.executeMethod(method);
        System.out.println(method.getStatusCode() + " " + method.getStatusText());
    }
    catch(HttpException ex){
        // Handle Exception
    }
    catch(IOException ex){
        // Handle Exception
    }
    
    0 讨论(0)
  • 2021-01-02 18:59

    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

    0 讨论(0)
提交回复
热议问题