Fork me on GitHub

web.py上传文件并解压

有个需求是从php端上传zip文件到python端并且解压到指定目录,以下是解决方法

1、python端,使用的web.py

def POST(self):
    post_data = web.input(myfile={})
   
    # 文件夹存在则删除,保证每次都是解压最新文件
    dir_path = post_data['dir_path']
    isExists = os.path.exists(dir_path)
    try:
        if not isExists:
            os.makedirs(dir_path, 0o777)
        else:
            os.system('sudo rm -rf ' + dir_path)
            os.makedirs(dir_path, 0o777)
    except:
        return False
   
    # 保存文件
    if 'myfile' in post_data: # to check if the file-object is created
        filepath=post_data.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.
        filename=filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension)
        fout = open(dir_path +'/'+ filename,'w') # creates the file where the uploaded file should be stored
        fout.write(post_data.myfile.file.read()) # writes the uploaded file to the newly created file.
        fout.close() # closes the file, upload complete.

    # 解压zip文件
    try:
        zip_ref = zipfile.ZipFile(dir_path + '/' + filename, 'r')
        zip_ref.extractall(dir_path )
        zip_ref.close()
        os.system('sudo rm -rf ' + dir_path + '/' + filename)
    except:
        return False

    return True

2、php端curl方法

<?php
$url = "/xx/yy";

$post_data = ['myfile' => new \CURLFILE($file_path), 'dir_path' => $dir_path];

$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, $post_data);
$output = curl_exec($ch);
curl_close($ch);

这里需要特别说明下,以下这种写法

$post_data = array(
            // 需要注意的是,在路径前必须带上@,不然只会当做是简单的键值对
            'pic'   =>  '@'.realpath($path)
            'name'  =>  'issac'
        );

只有在php5.5以下版本有效,换言之现在根本没有用,而且现在网上充斥的全是这种过时的失效版本,@字符什么,现在根本没有用了,很多资料并没有注明,害我调试了好久。

所以为了兼容不同版本,可以参考这个方法

function upload_file($url,$filename,$path,$type){
    //php 5.5以上的用法
    if (class_exists('\CURLFile')) {
        $data = array('file' => new \CURLFile(realpath($path),$type,$filename));
    } else {
        $data = array(
            'file'=>'@'.realpath($path).";type=".$type.";filename=".$filename
        );
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $return_data = curl_exec($ch);
    curl_close($ch);
    echo $return_data;
}

参考资料

http://webpy.org/cookbook/storeupload/

https://www.jianshu.com/p/63b32ceea742

https://my.oschina.net/forMemory/blog/374451

posted @ 2018-12-04 20:20  archer-wong  阅读(418)  评论(0编辑  收藏  举报