客户端(发送方)
使用HttpURLConnection
或第三方库如Apache HttpClient、OkHttp等来发送带有文件的POST请求
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileUploadExample {
public static void main(String[] args) throws IOException {
String url = "http://your-server.com/upload"; // 服务器接口地址
File file = new File("/path/to/your/local/file.txt"); // 要上传的文件
URL obj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
connection.setDoOutput(true);
DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
dos.writeBytes("--" + boundary + "\r\n");
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n");
dos.writeBytes("Content-Type: application/octet-stream\r\n\r\n");
InputStream fis = new FileInputStream(file);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
dos.write(buffer, 0, bytesRead);
}
fis.close();
dos.writeBytes("\r\n--" + boundary + "--\r\n");
dos.flush();
dos.close();
int responseCode = connection.getResponseCode();
System.out.println("Response Code : " + responseCode);
}
}
服务器端(接收方)
在服务器端,通过MultipartFile
来接收文件:
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.stereotype.Controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@Controller
public class FileUploadController {
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
File uploadDir = new File("upload-dir");
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
String fileName = file.getOriginalFilename();
File serverFile = new File(uploadDir.getAbsolutePath() + "/" + fileName);
FileOutputStream fos = new FileOutputStream(serverFile);
fos.write(bytes);
fos.close();
return "You successfully uploaded " + fileName + "!";
} catch (IOException e) {
e.printStackTrace();
return "Error during file upload!";
}
} else {
return "Please select a file to upload!";
}
}
}