1. 程式人生 > >php將上傳的檔案上傳到遠端伺服器

php將上傳的檔案上傳到遠端伺服器

問題場景還原如下: 現有一個上傳頁面,後端控制器用PHP來處理,但是PHP在得到上傳來的檔案時,要上傳給另一個介面(用golang實現的,記為api2)

api2原本也是處理簡單的上傳邏輯,但是不知道怎麼用php模擬上傳檔案給api2, (如果有同學知道,煩請告知,非常感謝) 最終採取瞭如下辦法: php將頁面上傳的檔案(記為file),將file的內容用base64編碼,作為一個普通的post請求的一個引數傳給api2, api2收到後,base64解碼,然後寫檔案,寫的檔案就是使用者上傳的檔案)。

程式碼如下:

<form enctype="multipart/form-data" method=
'post' action="/"> <input name="file" type="file" value="choose"> <input type="submit" value="Upload" name="submit"> </form> <?php function post_files($url, $file) { $data=array(); // 將檔案內容base64編碼當作post請求的一個引數 $data['file'] = base64_encode(file_get_contents($file
)); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $response = curl_exec($ch); curl_close
($ch); return $response; } if (isset($_POST["submit"])) { // Move file to a temp location $uploadDir = './upload/'; $uploadFile = $uploadDir . basename($_FILES['file']['name']); if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)){ // 這個就是api2地址: http://localhost:8080/upload $response = post_files('http://localhost:8080/upload', $uploadFile); echo $response; } else { echo "上傳失敗"; } } ?>

api2實現如下:

const uploadPath = "E:\\workspace\\go\\src\\gerrylon.top\\learnGo\\fileupload\\upload"

func main() {
	http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
		filecontentStr := r.PostFormValue("file")
		filecontents, _ := base64.StdEncoding.DecodeString(filecontentStr)

		// "test.jpg"請根據需要替換(可能需要再加一個欄位,將原始檔名傳過來)
		fp, _ := os.OpenFile(filepath.Join(uploadPath, "test.jpg"), os.O_CREATE, 0666)
		defer fp.Close()
		fp.Write(filecontents)
	})

	log.Fatal(http.ListenAndServe(":8080", nil))
}

歡迎補充指正。