java 上传人家到指定服务器
时间: 2023-11-21 17:05:12 浏览: 36
要将文件上传到指定的服务器,您可以使用Java中的URLConnection或Apache HttpClient来实现。下面是使用URLConnection实现文件上传的示例代码:
```java
import java.io.*;
import java.net.*;
public class FileUploader {
public static void main(String[] args) {
String filePath = "path/to/your/file";
String serverUrl = "http://example.com/upload";
File file = new File(filePath);
try {
URL url = new URL(serverUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + "*****");
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes("--" + "*****" + "\r\n");
outputStream.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + "\r\n");
outputStream.writeBytes("\r\n");
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.writeBytes("\r\n");
outputStream.writeBytes("--" + "*****" + "--" + "\r\n");
fileInputStream.close();
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 文件上传成功
} else {
// 文件上传失败
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
您需要将filePath和serverUrl替换为实际的文件路径和服务器URL。这段代码会将指定的文件上传到指定的服务器,并返回HTTP响应码来指示上传成功或失败。