3.2 傳送檔案資料

API: 傳檔

POST https://notes.webmix.cc/html5_tutorial/file/file_receive.php

Request Body

Name
Type
Description

the_file*

File 物件

傳遞檔案

後端 PHP 程式如下:

<?php
    header('Content-Type: text/html; charset=utf-8');  //傳送出去的編碼
    ini_set("display_errors", "On");
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: *');
    error_reporting(E_ALL & ~E_NOTICE);
    
    // 取得副檔名
    $new_array = explode(".", $_FILES['the_file']['name']);
    $ext = end($new_array);
    
    $target_dir = "./upload/"; // 目標路徑
    $new_filename = time() . "_" . rand(10,100) . "." . $ext; // 新的檔名
    $target_file = $target_dir . $new_filename; // 存的位置 + 檔名
    move_uploaded_file($_FILES["the_file"]["tmp_name"], $target_file);
    
    $arr = array('code' => "success", "file_path" => "https://notes.webmix.cc/html5_tutorial/file/upload/".$new_filename);
    echo json_encode($arr);
?>

建立 ajax/practice/xmlhttprequest_upload_file.html 檔案,內容如下:

Last updated