Denis Vlasenko | 250aa5b | 2008-04-17 12:35:09 +0000 | [diff] [blame] | 1 | POST upload example: |
| 2 | |
| 3 | post_upload.htm |
| 4 | =============== |
| 5 | <html> |
| 6 | <body> |
| 7 | <form action=/cgi-bin/post_upload.cgi method=post enctype=multipart/form-data> |
| 8 | File to upload: <input type=file name=file1> <input type=submit> |
| 9 | </form> |
| 10 | |
| 11 | |
| 12 | post_upload.cgi |
| 13 | =============== |
| 14 | #!/bin/sh |
| 15 | |
| 16 | # POST upload format: |
| 17 | # -----------------------------29995809218093749221856446032^M |
| 18 | # Content-Disposition: form-data; name="file1"; filename="..."^M |
| 19 | # Content-Type: application/octet-stream^M |
| 20 | # ^M <--------- headers end with empty line |
| 21 | # file contents |
| 22 | # file contents |
| 23 | # file contents |
| 24 | # ^M <--------- extra empty line |
| 25 | # -----------------------------29995809218093749221856446032--^M |
| 26 | |
| 27 | # Beware: bashism $'\r' is used to handle ^M |
| 28 | |
| 29 | file=/tmp/$$-$RANDOM |
| 30 | |
| 31 | # CGI output must start with at least empty line (or headers) |
| 32 | printf '\r\n' |
| 33 | |
| 34 | IFS=$'\r' |
| 35 | read -r delim_line |
| 36 | |
| 37 | IFS='' |
| 38 | delim_line="${delim_line}--"$'\r' |
| 39 | |
| 40 | while read -r line; do |
| 41 | test "$line" = '' && break |
| 42 | test "$line" = $'\r' && break |
| 43 | done |
| 44 | |
| 45 | # This will not work well for binary files: bash 3.2 is upset |
| 46 | # by reading NUL bytes and loses chunks of data. |
| 47 | # If you are not bothered by having junk appended to the uploaded file, |
| 48 | # consider using simple "cat >file" instead of the entire |
| 49 | # fragment below. |
| 50 | |
| 51 | while read -r line; do |
| 52 | |
| 53 | while test "$line" = $'\r'; do |
| 54 | read -r line |
| 55 | test "$line" = "$delim_line" && { |
| 56 | # Aha! Empty line + delimiter! All done |
| 57 | cat <<EOF |
| 58 | <html> |
| 59 | <body> |
| 60 | File upload has been accepted |
| 61 | EOF |
| 62 | exit 0 |
| 63 | } |
| 64 | # Empty line + NOT delimiter. Save empty line, |
| 65 | # and go check next line |
| 66 | printf "%s\n" $'\r' -vC >&3 |
| 67 | done |
| 68 | # Not empty line - just save |
| 69 | printf "%s\n" "$line" -vC >&3 |
| 70 | done 3>"$file" |
| 71 | |
| 72 | cat <<EOF |
| 73 | <html> |
| 74 | <body> |
| 75 | File upload was not terminated with '$delim_line' - ??! |
| 76 | EOF |