gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:15:18 26 4
gpt4 key购买 nike

我必须将文件上传到服务器,该服务器仅公开带有文件上传按钮的 jsf 网页(通过 http)。我必须自动生成一个文件并将文件上传到服务器的过程(作为 java 独立过程完成)。遗憾的是,必须将文件上传到的服务器不提供 FTP 或 SFTP。有办法做到这一点吗?

谢谢,里奇

最佳答案

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

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

否则该 Action 可能根本不会被调用。对于残余物,它与“常规”形式没有什么不同。流程基本如下:

  • 在带有表单的页面上发送 GET 请求。
  • 提取 JSESSIONID cookie。
  • 提取 javax.faces.ViewState 的值响应中的隐藏字段。如有必要(确定它是否具有动态生成的名称,因此可能会更改每个请求),提取输入文件字段的名称和提交按钮。 j_id 可识别动态生成的 ID/名称前缀。
  • 准备一个 multipart/form-data POST 请求。
  • 在该请求上设置 JSESSIONID cookie(如果不是 null)。
  • 设置javax.faces.ViewState的名值对隐藏字段和按钮。
  • 设置要上传的文件。

您可以使用任何 HTTP 客户端库来执行该任务。标准 Java SE API 提供 java.net.URLConnection为此,这是 pretty low level .为了减少冗长的代码,您可以使用 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);
// ...

关于java - 我如何以编程方式将文件上传到网站?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8623870/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com