如何以编程方式将文件上传到网站?

Ric*_*hie 3 java jsf file-upload

我必须将文件上传到服务器,该服务器只显示带有文件上传按钮的jsf网页(通过http).我必须自动化一个进程(作为java独立进程完成),它生成一个文件并将文件上传到服务器.然后,必须上传文件的服务器不提供FTP或SFTP.有没有办法做到这一点?

谢谢,里奇

Bal*_*usC 7

以编程方式提交JSF生成的表单时,您需要确保考虑以下3项内容:

  1. 维护HTTP会话(当然,如果网站启用了JSF服务器端状态保存).
  2. 发送javax.faces.ViewState隐藏字段的名称 - 值对.
  3. 发送虚拟按下按钮的名称 - 值对.

否则,可能根本不会调用该操作.对于残余,它与"常规"形式没有区别.流程基本如下:

  • 使用表单在页面上发送GET请求.
  • 解压缩JSESSIONID cookie.
  • javax.faces.ViewState从响应中提取隐藏字段的值.如果有必要(确保它具有动态生成的名称,因此可能更改每个请求),请提取输入文件字段的名称和提交按钮.动态生成的ID /名称可由j_id前缀识别.
  • 准备multipart/form-dataPOST请求.
  • null在该请求上设置JSESSIONID cookie(如果没有).
  • 设置javax.faces.ViewState隐藏字段的名称 - 值对和按钮.
  • 设置要上载的文件.

您可以使用任何HTTP客户端库来执行该任务.标准的Java SE API java.net.URLConnection为此提供了相当低的水平.为了减少冗长的代码,您可以使用Apache HttpClient来执行HTTP请求并管理cookie,并使用Jsoup从HTML中提取数据.

这是一个启动示例,假设页面只有一个<form>(否则您需要在Jsoup的CSS选择器中包含该表单的唯一标识符):

String url = "http://localhost:8088/playground/test.xhtml";
String viewStateName = "javax.faces.ViewState";
String submitButtonValue = "Upload"; // Value of upload submit button.

HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore());

HttpGet httpGet = new HttpGet(url);
HttpResponse getResponse = httpClient.execute(httpGet, httpContext);
Document document = Jsoup.parse(EntityUtils.toString(getResponse.getEntity()));
String viewStateValue = document.select("input[type=hidden][name=" + viewStateName + "]").val();
String uploadFieldName = document.select("input[type=file]").attr("name");
String submitButtonName = document.select("input[type=submit][value=" + submitButtonValue + "]").attr("name");

File file = new File("/path/to/file/you/want/to/upload.ext");
InputStream fileContent = new FileInputStream(file);
String fileContentType = "application/octet-stream"; // Or whatever specific.
String fileName = file.getName();

HttpPost httpPost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
entity.addPart(uploadFieldName, new InputStreamBody(fileContent, fileContentType, fileName));
entity.addPart(viewStateName, new StringBody(viewStateValue));
entity.addPart(submitButtonName, new StringBody(submitButtonValue));
httpPost.setEntity(entity);
HttpResponse postResponse = httpClient.execute(httpPost, httpContext);
// ...
Run Code Online (Sandbox Code Playgroud)