使用 BASH 作为 CGI 进行 HTTP 文件上传

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

#!/usr/bin/env bash
newline=""
boundary="" while true; do
read newline
line_start=$(expr substr "$newline" ) 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
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>
上一篇:实验一(不知道怎么上传.docx格式)


下一篇:Machine Learning, Homework 9, Neural Nets