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

10 篇文章 1 订阅

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

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值