我的ajax应用程序从用户的浏览器将文件上传到Java应用程序容器。我想做的是:一旦上传完成,我想将文件“发送”到WebDAV服务器,由主机名(即localhost),端口(即8080)和我想要的位置标识存储文件(即dir1 / dir2)。
我所追求的基本上是一个WebDAV客户端框架,使我能够将文件上传到WebDAV。在我的应用程序中,我已经在使用“webdavclient4j”,但我似乎找不到用它上传文件的方法?
有什么想法吗?提前感谢您提供的任何帮助。
˚F
答案 0 :(得分:12)
使用我最近发布的,易于使用的现代webdav客户端java,Sardine,只需几行代码即可完成。这是一些例子(第一个使用commons-io来读取文件):
Sardine sardine = SardineFactory.begin("username", "password");
byte[] data = FileUtils.readFileToByteArray(new File("/file/on/disk"));
sardine.put("http://yourdavserver.com/adirectory/nameOfFile.jpg", data);
或使用流:
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
欢呼声,
乔恩
答案 1 :(得分:7)
您可以使用Jackrabbit WebDAV Library。
将内容上传到WebDAV服务器的WebDAV客户端示例(取自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
}