概述
PHP发送方代码段:
PS : 如果 PHP Version < 7.0请去掉 CURLFile 类型强调标识
<?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
close(_write)
respo.HttpHSucc(c, "Success !", nil, res, "")
return
}
写这的原因是:
1.因为使用socket传Buff输出会造成文件完整性幻读,还要检测文件大小完整性很麻烦.
2.然后就是不需要使用服务器软件转发
再给大家介绍个不支持php语言的文件对象传输组件---Minio
最后
以上就是端庄吐司为你收集整理的PHP使用CURL向Python,Golang发送文件表单上传文件[HTTP协议]的全部内容,希望文章能够帮你解决PHP使用CURL向Python,Golang发送文件表单上传文件[HTTP协议]所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复