在Java中,上传本地文件到服务器通常使用`HttpURLConnection`类或者第三方库如Apache HttpClient、OkHttp等。以下是一个使用`HttpURLConnection`类上传文件的简单示例:
```java
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileUploadExample {
public static void uploadFile(String filePath, String serverURL) {
HttpURLConnection connection = null;
try {
// 创建URL对象
URL url = new URL(serverURL);
// 打开连接
connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 设置允许输出
connection.setDoOutput(true);
// 设置请求头
connection.setRequestProperty("Content-Type", "multipart/form-data");
// 设置连接超时和读取超时
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
// 创建文件输入流
FileInputStream fileInputStream = new FileInputStream(filePath);
// 创建数据输出流
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
// 写入文件信息
String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
outputStream.writeBytes("--" + boundary + "rn");
outputStream.writeBytes("Content-Disposition: form-data; name="file"; filename="" + filePath + ""rn");
outputStream.writeBytes("Content-Type: " + URLConnection.guessContentTypeFromName(filePath) + "rn");
outputStream.writeBytes("Content-Transfer-Encoding: binaryrn");
outputStream.writeBytes("rn");
// 写入文件内容
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);