Java 上传文件到远程服务器
在 Java 中,有几种常见的方法可以将文件上传到远程服务器,以下是几种实现方式:

使用 HTTP/HTTPS (基于 Web 服务)
使用 Apache HttpClient
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
public class FileUploader {
public static void main(String[] args) {
String serverUrl = "http://example.com/upload";
File fileToUpload = new File("path/to/your/file.txt");
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost uploadFile = new HttpPost(serverUrl);
FileBody fileBody = new FileBody(fileToUpload);
HttpEntity entity = MultipartEntityBuilder.create()
.addPart("file", fileBody)
.build();
uploadFile.setEntity(entity);
HttpResponse response = httpClient.execute(uploadFile);
HttpEntity responseEntity = response.getEntity();
String responseString = EntityUtils.toString(responseEntity);
System.out.println("Server response: " + responseString);
} catch (IOException e) {
e.printStackTrace();
}
}
}
添加依赖 (Maven)
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
使用 FTP/SFTP
使用 Apache Commons Net (FTP)
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.FileInputStream;
import java.io.IOException;
public class FtpUploader {
public static void main(String[] args) {
String server = "ftp.example.com";
int port = 21;
String user = "username";
String pass = "password";
String remoteFilePath = "/remote/path/file.txt";
String localFilePath = "path/to/your/file.txt";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
FileInputStream inputStream = new FileInputStream(localFilePath);
boolean done = ftpClient.storeFile(remoteFilePath, inputStream);
inputStream.close();
if (done) {
System.out.println("File uploaded successfully");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
添加依赖 (Maven)
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.8.0</version>
</dependency>
使用 JSch (SFTP)
import com.jcraft.jsch.*;
import java.io.FileInputStream;
import java.io.InputStream;
public class SftpUploader {
public static void main(String[] args) {
String host = "sftp.example.com";
int port = 22;
String user = "username";
String password = "password";
String remoteFilePath = "/remote/path/file.txt";
String localFilePath = "path/to/your/file.txt";
JSch jsch = new JSch();
Session session = null;
Channel channel = null;
InputStream inputStream = null;
try {
session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
inputStream = new FileInputStream(localFilePath);
sftpChannel.put(inputStream, remoteFilePath);
System.out.println("File uploaded successfully");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) inputStream.close();
if (channel != null) channel.disconnect();
if (session != null) session.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
添加依赖 (Maven)
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
使用 SSH (SCP)
import com.jcraft.jsch.*;
public class ScpUploader {
public static void main(String[] args) {
String host = "ssh.example.com";
int port = 22;
String user = "username";
String password = "password";
String remoteFilePath = "/remote/path/file.txt";
String localFilePath = "path/to/your/file.txt";
JSch jsch = new JSch();
Session session = null;
Channel channel = null;
try {
session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
String command = "scp -p " + localFilePath + " " + user + "@" + host + ":" + remoteFilePath;
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.connect();
System.out.println("File uploaded successfully");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (channel != null) channel.disconnect();
if (session != null) session.disconnect();
}
}
}
使用 Spring Boot (Web 服务端)
如果你需要构建一个完整的上传服务,可以使用 Spring Boot:
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
try {
// 保存文件到本地或远程服务器
String fileName = file.getOriginalFilename();
File dest = new File("/path/to/save/" + fileName);
file.transferTo(dest);
return "File uploaded successfully: " + fileName;
} catch (IOException e) {
return "Failed to upload file: " + e.getMessage();
}
}
}
注意事项
- 安全性:在生产环境中,不要硬编码凭据,应使用配置文件或环境变量
- 错误处理:添加适当的错误处理和日志记录
- 性能:对于大文件,考虑使用分块上传或进度监控
- 超时设置:根据网络环境设置合理的超时时间
- SSL/TLS:对于敏感数据,始终使用加密连接
选择哪种方法取决于你的具体需求,如服务器类型、安全要求和网络环境等。

