zoukankan      html  css  js  c++  java
  • 使用 BASH 作为 CGI 进行 HTTP 文件上传

    憋半天憋出这么点代码来,暂时凑合可以用:

    #!/usr/bin/env bash
    newline=""
    boundary=""
    
    while true; do
        read newline
        line_start=$(expr substr "$newline" 1 15)
    
        if [ "${line_start}x" == "Content-Type: mx" ]; then
            boundary=$(echo $newline|awk '{print substr($3,10);}' )
        fi
    
        if [ "${newline}" == --${boundary} ]; then
            read newline
            read newline
            read newline
    
            IFS="--${boundary}" read -r newline
    
            echo $newline > /opt/myapp/update.sh
    
            echo "OK"
    
            exit 0
        fi
    done

    说一下思路:

    1. 找到 boundary 字段。boundary 是经过统计的,在文件中无法找到的字段,以此作为文件内容的边界分割符。

    2. 匹配 boundary。boundary 是文件传输的开始,但是,接下来还有三行协议内容(测试了IE、FireFox、Chrome,都一样),这里的处理方式是忽略。

    3. 将 boundary 指定为 read 的行间分割符,然后 read 读取“一行”。

    4. 将内容进行解码,并重定向到文件。

    需要注意,因为 read 和 echo 的关系,处理二进制文件可能出错,所以,发送二进制文件前,最好对其进行 base64 编码。(编码 base64 source_file; 解码 base64 -d coded_file).

    勉强可用,有空再做仔细点。

    HTML 代码用的是这个:

    <meta http-equiv=Content-Type content="text/html;charset=utf-8">
    
    <html>
    
    <body>
    <form enctype="multipart/form-data" action="http://localhost/UploadFile" method="post">
    file1:<input type="file" name="file1"><br>
    <input type="submit" value="上传">
    <input type="reset" value="重置">
    </form>
    </body>
    
    </html> 
  • 相关阅读:
    词向量的发展
    拉格朗日对偶理解
    EM算法理解
    Xgboost理解
    GBDT理解
    深入理解KS
    PCA主成分分析理解
    SVM理解
    Python调用C++
    Linux opencv安装与编译
  • 原文地址:https://www.cnblogs.com/pied/p/4754763.html
Copyright © 2011-2022 走看看