Прежде всего, почему бы вам просто не отправить форму непосредственно в этот скрипт PHP?
<form action="http://example.com/upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
Если это как-то не так, и вам действительно нужно отправить форму сервлету, то сначала создайте форму HTML, как показано в JSP:
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
В сервлете, который прослушивает url-pattern
из /upload
, у вас есть 2 варианта обработки запроса, в зависимости от того, что принимает скрипт PHP.
Если PHP-скрипт принимает те же самые параметры и может обрабатывать загруженный файл так же, как HTML-форма указала сервлету (я все равно предпочел бы просто отправить форму непосредственно в PHP). сценария, но в любом случае), тогда вы можете позволить сервлету играть прозрачный прокси, который просто немедленно передает байты из HTTP-запроса в сценарий PHP. java.net.URLConnection
API полезен в этом.
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-скрипт принимает другие или другие параметры (опять же, я бы предпочел просто соответствующим образом изменить HTML-форму, чтобы она могла напрямую отправляться в PHP-скрипт), тогда вы можно использовать Apache Commons FileUpload для извлечения загруженного файла и Apache HttpComponents Client для отправки загруженного файла в сценарий PHP, как если бы он был отправлен из HTML-формы.
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.
}
}
Смотри также: