java 上传文件远程调用
时间: 2025-03-18 17:19:57 浏览: 28
### Java实现文件上传的远程接口调用
在Java中,可以通过多种方式实现文件上传的远程接口调用。以下是基于`Socket`和`RESTful API`两种常见的方式。
#### 使用Socket实现文件上传
通过`Socket`可以实现在客户端和服务端之间传输数据的功能。下面是一个简单的示例:
```java
// 客户端代码
import java.io.*;
import java.net.Socket;
public class FileUploadClient {
public static void main(String[] args) throws IOException {
String serverAddress = "localhost";
int port = 8080;
try (Socket socket = new Socket(serverAddress, port);
OutputStream out = socket.getOutputStream();
FileInputStream fis = new FileInputStream("example.txt")) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead); // 将文件内容写入到Socket流中[^2]
}
} catch (IOException e) {
System.out.println("Error uploading file: " + e.getMessage());
}
}
}
```
服务端接收文件并保存:
```java
// 服务端代码
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class FileUploadServer {
public static void main(String[] args) throws IOException {
int port = 8080;
ServerSocket serverSocket = new ServerSocket(port);
try (Socket clientSocket = serverSocket.accept(); // 接受客户端连接
InputStream in = clientSocket.getInputStream();
FileOutputStream fos = new FileOutputStream("received_example.txt")) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead); // 将接收到的数据写入本地文件
}
} finally {
serverSocket.close();
}
}
}
```
---
#### 使用RESTful API实现文件上传
对于现代应用开发,通常推荐使用HTTP协议并通过`RESTful API`完成文件上传功能。以下是一个基于Spring Boot框架的简单示例。
##### Spring Boot服务端配置
创建一个控制器用于处理文件上传请求:
```java
@RestController
@RequestMapping("/upload")
public class FileUploadController {
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
// 获取目标路径
Path path = Paths.get("uploads/" + file.getOriginalFilename());
// 将文件保存至指定位置
Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
return ResponseEntity.ok("File uploaded successfully!");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
} else {
return ResponseEntity.badRequest().body("Please select a file to upload.");
}
}
}
```
##### 客户端发送文件
利用`HttpClient`或其他工具向服务端发起POST请求:
```java
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.File;
public class RestFileUploader {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/upload");
File file = new File("example.txt");
HttpEntity entity = MultipartEntityBuilder.create()
.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, file.getName())
.build();
post.setEntity(entity);
try (CloseableHttpResponse response = httpClient.execute(post)) {
System.out.println(response.getStatusLine().getStatusCode() + ": " + response.getStatusLine().getReasonPhrase());
}
}
}
```
上述代码展示了如何通过`Multipart/form-data`形式提交文件给服务端[^4]。
---
### 总结
以上分别介绍了基于`Socket`和`RESTful API`的文件上传方案。前者适合低层通信需求场景;后者则更适用于现代化Web应用程序开发环境下的文件传输操作。
阅读全文
相关推荐




















