如何接收文件并将其发送到不同的服务器

时间:2014-03-30 13:52:31

标签: java servlets post file-upload web

我有一台可以让用户上传文件的服务器。用户上传文件后,我向此服务器发送一个帖子请求 在doGet方法中,我这样做了:

  if (path.endsWith("/upload")) {
    out.println("<html>");
    out.println("<body>");
    out.print("<form action=\"/MySelf/upload\" method=\"POST\" enctype=\"multipart/form-data\">");
    out.print("<input name=\"file\" type=\"file\" size=\"50\">");
    out.print("<input name=\"submit\" type=\"submit\" value=\"submit\">");
    out.print("</form>");
    out.println("</body>");
    out.println("</html>");
    }

在doPost方法中,我可以这样做:

if (path.endsWith("/upload")) {
    Part filePart = request.getPart("file"); 
    String filename = getFilename(filePart);

    //Wanna send this filePart to other servers(for example:127.0.0.1:8888,127.0.0.1:8889 etc.)
}

现在,我想将此filePart发送到其他服务器,如何使用HttpURLConnection执行此操作?

1 个答案:

答案 0 :(得分:1)

此处将代码发送到另一台服务器的代码。感谢Mykong关于通过HttpURLConnection发送帖子的教程。这个方法的大部分来自该教程

 // HTTP POST request, sends data in filename to the hostUrl
 private void sendPost(String hostUrl, String filename) throws Exception {

    URL url = new URL(hostUrl);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "testUA");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    // Send post request
    con.setDoOutput(true);
    DataOutputStream remoteStream = new DataOutputStream(con.getOutputStream());

    byte[] fileBuffer = new byte[1024];
    FileInputStream partFile = new FileInputStream(filename);
    BufferedInputStream bufferedStream = new BufferedInputStream(partFile);

    //read from local filePart file and write to remote server
    int bytesRead = -1;
    while((bytesRead = bufferedStream.read(fileBuffer)) != -1)
    {
       remoteStream.write(fileBuffer, 0, bytesRead);
    }

    bufferedStream.close();

    remoteStream.flush();
    remoteStream.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + hostUrl);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
          new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    //read server repsonse
    while ((inputLine = in.readLine()) != null) {
       response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println("Host responded: ");
    System.out.println(response.toString());

 }

然后从servlet接受上传数据的部分调用此方法:

if (path.endsWith("/upload")) {
    Part filePart = request.getPart("file"); 
    String filename = getFilename(filePart);

   //send it to a server
   sendPost("http://127.0.0.1:8888", filename);