在服务器间传输图像?

use*_*114 5 php jsp servlets

我有一个java servlet,它接受用户上传到我的web应用程序的图像.

我有另一台服务器(运行php),它将托管所有图像.如何从我的jsp服务器获取图像到我的php服务器?流程将是这样的:

public class ServletImgUpload extends HttpServlet 
{   
    public void doPost(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException 
    {
        // get image user submitted
        // try sending it to my php server now
        // return success or failure message back to user
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Bal*_*usC 0

首先,为什么不直接将表单提交到 PHP 脚本呢?

<form action="http://example.com/upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit">
</form>
Run Code Online (Sandbox Code Playgroud)

如果这不是一个选项,并且您确实需要将表单提交到 servlet,那么首先在 JSP 中创建一个 HTML 表单,如下所示:

<form action="upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit">
</form>
Run Code Online (Sandbox Code Playgroud)

在侦听 of 的 servlet 中url-pattern/upload您有 2 个选项来处理请求,具体取决于 PHP 脚本的处理方式。

如果 PHP 脚本采用相同的参数,并且可以按照 HTML 表单指示 servlet 执行的相同方式处理上传的文件(我仍然宁愿让表单直接提交给 PHP 脚本,但无论如何),那么您可以让 servlet 充当透明代理,它只是立即将字节从 HTTP 请求传输到 PHP 脚本。APIjava.net.URLConnection在这方面很有用。

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.
}
Run Code Online (Sandbox Code Playgroud)

如果 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.
    }
}
Run Code Online (Sandbox Code Playgroud)

也可以看看: