首先,为什么不要求你直接将表格提交给该政策手册?
<form action="http://example.com/upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
如果这不是一种选择,而且你真的需要将表格提交服务器,那么首先在联合调查组中形成一种超文本形式:
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
在关于<代码>/upload的的服务器中,根据PHP的文字处理申请有两种选择。
如果PHP的文字采用same参数,并且能够处理上载文件,其方式与超文本格式指示服务器做的相同(我仍然只是让表格直接提交给PHP的文字,但不管怎么说),那么你可以让该信封为透明的代理玩.,而该代理只是从吉卜赛人的请求中立即将 by转给PHP。 java.net.URLConnection
就此而言,APIC是有用的。
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpURLConnection connection = (HttpURLConnection) new URL("http://example.com/upload.php").openConnection();
connection.setDoOutput(true); // POST.
connection.setRequestProperty("Content-Type", request.getHeader("Content-Type")); // This one is important! You may want to check other request headers and copy it as well.
// Set streaming mode, else HttpURLConnection will buffer everything in Java s memory.
int contentLength = request.getContentLength();
if (contentLength > -1) {
connection.setFixedLengthStreamingMode(contentLength);
} else {
connection.setChunkedStreamingMode(1024);
}
InputStream input = request.getInputStream();
OutputStream output = connection.getOutputStream();
byte[] buffer = new byte[1024]; // Uses only 1KB of memory!
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
output.close();
InputStream phpResponse = connection.getInputStream(); // Calling getInputStream() is important, it s lazily executed!
// Do your thing with the PHP response.
}
如果PHP的文字包含 different或more参数(ain,我只是改动超文本格式,以便它能够直接提交PHP的文字,那么,如果用户使用,Apache Commons 文档上载,以提取上载文档和
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
InputStream fileContent = null;
String fileContentType = null;
String fileName = null;
try {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField() && item.getFieldName().equals("file")) { // <input type="file" name="file">
fileContent = item.getInputStream();
fileContentType = item.getContentType();
fileName = FilenameUtils.getName(item.getName());
break; // If there are no other fields?
}
}
} catch (FileUploadException e) {
throw new ServletException("Parsing file upload failed.", e);
}
if (fileContent != null) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/upload.php");
MultipartEntity entity = new MultipartEntity();
entity.addPart("file", new InputStreamBody(fileContent, fileContentType, fileName));
httpPost.setEntity(entity);
HttpResponse phpResponse = httpClient.execute(httpPost);
// Do your thing with the PHP response.
}
}
See also: