首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java SE 實戰:HTTP 協議上傳圖片到 PHP 接口

     編輯:Java 綜合教學

核心思路

構造 multipart/form-data 請求體,模擬瀏覽器表單上傳,PHP 端用 $_FILES 接收並 move_uploaded_file 保存。

Java 客戶端代碼

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 接收端 (test.php)

<?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>

關鍵點

  • Boundary 隨機字符串,頭尾格式固定
  • Content-Disposition 指定字段名與文件名
  • PHP 端 $_FILES['img']['tmp_name'] 為臨時文件路徑
  • 適用於 Android/Java 客戶端上傳文件到 PHP/Java/Python 等後端
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved