使用python在php表单上自动提交文件

时间:2016-01-08 16:21:33

标签: php python forms

我在PHP上运行了带有文件上传脚本的服务器,我在index.php中输入了该脚本。我想自动将指定路径上的图像文件上传到服务器。

PHP代码:

<?php
if(isset($_POST['submit'])){
if(isset($_FILES['file'])){
    $err=array();
    $f_name=$_FILES['file']['name'];
    //echo $f_name;
    $size=$_FILES['file']['size'];
    $type=$_FILES['file']['type'];
    $file_tmp =$_FILES['file']['tmp_name'];
    echo $file_tmp;
    $file_ext=strtolower(end(explode('.',$_FILES['file']['name'])));
    $allowed_ext= array('jpg','jpeg','png');
    if(in_array($file_ext,$allowed_ext)==FALSE){
        $err[]="extension not allowed";

    }
    if($size > 1000000){
        $err[]='size is greater than 1MB';
    }
    if(empty($err)==TRUE){
        //chmod('upload_image',755);
        echo $_FILES['file']['tmp_name'];
        $newname = dirname(__FILE__).'/upload_image/'.$f_name;
        move_uploaded_file($_FILES['file']['tmp_name'],$newname);
        echo 'success';
    }
    else{
        print_r($err);
    }
}





}

?>

<hr>
<form action="upload.php" method="post" enctype="multipart/form-data">
    Upload your file here:<br>
    <input type="file" name="file" />
    <input type="submit" name="submit" value="submit"/>
</form>

现在我尝试使用python脚本自动化表单提交,例如:

def upload_file(path):
        url='http://localhost/phptestprogram/upload.php'
        files = {file: open(path,'rb')}
        r = requests.post(url, files=files)
        print r.text

但我无法达到我的结果。

1 个答案:

答案 0 :(得分:1)

你的php脚本在处理文件之前正在检查isset($_POST['submit']),但你的python似乎没有设置post变量submit。你可能需要做类似的事情:

r = requests.post(url, data = {"submit": "submit"}, files = files)