構造 multipart/form-data 請求體,模擬瀏覽器表單上傳,PHP 端用 $_FILES 接收並 move_uploaded_file 保存。
public class HttpUpload {
public static final String API = "https://localhost/test.php";
public static void main(String[] args) throws Exception {
String result = uploadImg("E:\\11.png");
System.out.println(result);
}
private static String uploadImg(String imgUrl) throws Exception {
File imgFile = new File(imgUrl);
HttpURLConnection conn = (HttpURLConnection) new URL(API).openConnection();
conn.setConnectTimeout(10000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=----123456789");
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
// 請求頭部分
StringBuilder head = new StringBuilder();
head.append("------123456789\r\n");
head.append("Content-Disposition: form-data; name='img'; filename='").append(imgFile.getName()).append("'\r\n");
head.append("Content-Type: image/jpeg\r\n\r\n");
os.write(head.toString().getBytes());
// 文件二進制內容
try (FileInputStream is = new FileInputStream(imgFile)) {
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) os.write(buffer, 0, len);
}
// 結束邊界
os.write("\r\n------123456789--".getBytes());
os.flush();
// 讀取響應
try (InputStream input = conn.getInputStream()) {
byte[] res = new byte[1024];
int resLen = input.read(res);
return new String(res, 0, resLen);
}
}
}
<?php
class Test {
public static function main() {
header("content-type:text/html;charset=utf-8");
if (!empty($_FILES)) {
(new Test())->uploadImg();
exit;
}
}
public function uploadImg() {
$res = move_uploaded_file($_FILES['img']['tmp_name'], './'.$_FILES['img']['name']);
echo $res ? "upload success" : "upload error";
}
}
Test::main();
?>
<form enctype="multipart/form-data" action="test.php" method="post">
<input type="file" name="img" />
<input type="submit" value="上傳" />
</form>
Content-Disposition 指定字段名與文件名$_FILES['img']['tmp_name'] 為臨時文件路徑