Bash cgi upload file

2019-08-02 07:22发布

问题:

Hello i have such problem. I have html

<form action="/cgi-bin/echo.cgi" method="post" enctype="multipart/form-data">
    <label for="file">Filename:</label>
    <input type="file" name="file" id="file"><br>
    <input type="submit" name="submit" value="Submit">
</form>

And i need to write this file from form to server using bash cgi(not perl). I try something like this

POST=$(</dev/stdin)
echo "$POST">"/tmp/a"

but it doesn't work

P.S. i see this in apache log /var/www/cgi-bin/echo.cgi: line 6: /dev/stdin: No such device or address

P.S.2 it works for me

if [ $REQUEST_METHOD == 'POST' ]; then
    if [ "$CONTENT_LENGTH" -gt 0 ]; then
        while read i; 
            do echo "$i";
        done
    fi
fi

but i have such output

------WebKitFormBoundary8WbSWxBe8rIaCMLG
Content-Disposition: form-data; name="file"; filename="ca.cpp"
Content-Type: text/x-c++src

#include <iostream>
int main(){
for(int x = 0; x <= 5; ++x)
for(int y = 0; y <=5; ++y)
std::cout << "x= " << x << " y= " << y << " f1= " << (x-2)*(x-2) + (y-1)*(y-1) << " f2= " << (x-2)*(x-2) + (y-5)*(y-5)<<std::endl;

}

------WebKitFormBoundary8WbSWxBe8rIaCMLG
Content-Disposition: form-data; name="submit"

Submit
------WebKitFormBoundary8WbSWxBe8rIaCMLG--

How i can parse content of my file?

回答1:

You should quote the variable:

echo "$POST" > /tmp/a

Otherwise, word splitting and wildcard expansion happens, which will cause whitespace to be merged and everything will be on a single line.

In general, you should always quote variables unless you have a good reason not to. There are some circimstances where it's not needed, but it never hurts unless you actually need word splitting.



标签: bash cgi