PHP使用CURL向Python,Golang傳送檔案表單上傳檔案[HTTP協議下Api]
阿新 • • 發佈:2018-12-16
PHP傳送方程式碼段:
<?php /** * htppCurl表單上傳檔案 * @param $file FILE_ADDR * @param string $url uri * @param string $key key * @return bool|mixed * @author Bill */ function curlSendFile(CURLFile $file, $url = '', $key = "123456") { if ($file == null || $url == '') return false; $post_data = []; $post_data["file"] = $file; $post_data["key"] = $key; return postCurl($url, $post_data); } /** * CurlPost請求 * @param $url * @param $data * @return mixed */ function postCurl($url, $data) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $output = curl_exec($ch); curl_close($ch); return $output; } //Demo : $url = "http://127.0.0.1:3000/upload"; $res = curlSendFile(new CURLFile('xxxxx.txt'), $url); var_dump($res);
Python接收端[Flask版]
# -*- coding:utf-8 -*- import datetime import os __authro__ = 'Bill' from flask import Flask from flask import request from flask import jsonify from flask_script import Manager, Server from werkzeug.utils import secure_filename app = Flask(__name__) app.debug = True manager = Manager(app) manager.add_command('runServ', Server(host='127.0.0.1', port=3000)) SUCC_CODE = 1 ERROR_CODE = 0 def get_file_dir(): return os.path.dirname(os.path.abspath(__file__)) + "\\" def response_message(data=[], message='Success !', code=SUCC_CODE): nowDatetime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') resInfo = {'code': None, 'data': None, 'msg': None, 'timestamp': nowDatetime} resInfo['data'] = data resInfo['msg'] = message resInfo['code'] = code return jsonify(resInfo) @app.route('/upload', methods=['POST']) def upload(): message = "上傳成功!" f = request.files['file'] if not f: message = "上傳失敗!" return response_message([], message, ERROR_CODE) fname = secure_filename(f.filename) f.save(os.path.join("./", fname)) return response_message([], message) if __name__ == "__main__": manager.run()
Golang接收端業務[Gin版]:
package upload import ( "github.com/gin-gonic/gin" "os" "io" "upfile/utils/respo" "strings" "mime/multipart" "upfile/config" "upfile/utils/filecheck" ) func UploadFile(c *gin.Context) { filename := strings.TrimSpace(c.DefaultPostForm("filename", "")) key := strings.TrimSpace(c.DefaultPostForm("key", "")) if filename == "" { respo.HttpErr(c, "Filename is empty!", nil, "") return } var skey = config.GetGconfig("uploadFile", "key") var _saveDir = config.GetGconfig("uploadFile", "destdir") if key == "" || key != skey { respo.HttpErr(c, "Key is err!", nil, "") return } file, _, err := c.Request.FormFile("file") if err != nil { respo.HttpErr(c, "File is err!", nil, "") return } savePath := _saveDir + "\\" + filename if res1, _ := filecheck.PathExists(_saveDir); res1 == false { respo.HttpErr(c, "The dir is not exist ! Please create a directory for storage !", nil, "") return } _write := make(chan int64) go func(file multipart.File, savePath string, write chan int64) { out, _ := os.Create(savePath) defer out.Close() writen, _ := io.Copy(out, file) _write <- writen }(file, savePath, _write) var res = map[string]interface{}{} res["filename"] = filename res["savePath"] = savePath res["fileSize"] = <-_write respo.HttpHSucc(c, "Success !", nil, res, "") return }
寫這的原因是:
1.因為使用socket傳Buff輸出會造成檔案完整性幻讀,還要檢測檔案大小完整性很麻煩.
2.然後就是不需要使用伺服器軟體轉發
再給大家介紹個不支援php語言的檔案物件傳輸元件---Minio