Ric*_*hie 3 java jsf file-upload
我必须将文件上传到服务器,该服务器只显示带有文件上传按钮的jsf网页(通过http).我必须自动化一个进程(作为java独立进程完成),它生成一个文件并将文件上传到服务器.然后,必须上传文件的服务器不提供FTP或SFTP.有没有办法做到这一点?
谢谢,里奇
以编程方式提交JSF生成的表单时,您需要确保考虑以下3项内容:
javax.faces.ViewState
隐藏字段的名称 - 值对.否则,可能根本不会调用该操作.对于残余,它与"常规"形式没有区别.流程基本如下:
javax.faces.ViewState
从响应中提取隐藏字段的值.如果有必要(确保它具有动态生成的名称,因此可能更改每个请求),请提取输入文件字段的名称和提交按钮.动态生成的ID /名称可由j_id
前缀识别.multipart/form-data
POST请求.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)