gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:12:31 26 4
gpt4 key购买 nike

我有一个服务器可以让用户上传文件。用户上传文件后,我向该服务器发送一个post请求在 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 来执行此操作?

最佳答案

以下是将文件发送到另一台服务器的代码。感谢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);

关于java - 如何接收文件并将其发送到不同的服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22744770/

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