PHP使用CURL向Python,Golang发送文件表单上传文件[HTTP协议下Api]

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ycc297876771/article/details/81077643

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

猜你喜欢

转载自blog.csdn.net/ycc297876771/article/details/81077643