image - 使用 netcat 提供包含图像的 HTTP 响应

标签 image bash http netcat

我正在尝试使用 netcat 编写一个小型 HTTP 服务器。对于纯文本文件,这工作正常,但当我尝试发送图片时,浏览器仅显示损坏图像的图标。 我所做的是提取所请求文件的 mime 类型和大小,并将其发送给客户端。 我的示例图片的请求 header 如下所示:

HTTP/1.0 200 OK
Content-Length: 197677 
Content-Type: image/jpeg

这是我使用 netcat 工具的 -e 选项启动的 bash 脚本:

#!/bin/bash

# -- OPTIONS
index_page=index.htm
error_page=notfound.htm

# -- CODE

# read request
read -s input
resource=$(echo $input | grep -P -o '(?<=GET \/).*(?=\ )') # extract requested file
[ ! -n "$resource" ] && resource=$index_page # if no file requested, set to default
[ ! -f "$resource" ] && resource=$error_page # if requested file not exists, show error pag

# generate output
http_content_type=$(file -b --mime-type $resource) # extract mime type
case "$(echo $http_content_type | cut -d '/' -f2)" in
    html|plain)
        output=$(cat $resource)

        # fix mime type for plain text documents
        echo $resource | grep -q '.css$' && http_content_type=${http_content_type//plain/css}
        echo $resource | grep -q '.js$' && http_content_type=${http_content_type//plain/javascript}
    ;;

    x-php)
        output=$(php $resource)
        http_content_type=${http_content_type//x-php/html} # fix mime type
    ;;

    jpeg)
        output=$(cat $resource)
    ;;

    png)
        output=$(cat $resource)
    ;;

    *)
        echo 'Unknown type'
esac

http_content_length="$(echo $output | wc -c | cut -d ' ' -f1)"

# sending reply
echo "HTTP/1.0 200 OK"
echo "Content-Length: $http_content_length"
echo -e "Content-Type: $http_content_type\n"
echo $output

如果有人能帮助我,我会很高兴:-)

最佳答案

我希望二进制数据中的特殊字符在您的 shell 脚本中处于事件状态。

我建议您通过以下方式获取文件大小:

http_content_length=`stat -c '%s' $resource`

然后您“发送”它:

...
echo -e "Content-Type: $http_content_type\n"
cat $resource

关于image - 使用 netcat 提供包含图像的 HTTP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15662262/

相关文章:

android - 我如何在我的 ScrollView 中调整我的 ImageView 的大小,因为它在这个图像中完成?

python - PIL.Image模块中各种图像缩放算法有什么区别?

javascript - Node中使用FFMPEG处理录屏的帧数

javascript - 有没有办法在每个 $http.get 上禁用 $digest 的触发?

html - 我可以指定用户名和密码以通过 HTTP 访问文件吗?

html - 使用 HTTP Post 将 secret 数据发送到服务器的安全方法

image - 是否通过除以 255 个训练集和测试集之间的泄漏信息来标准化图像?

linux - 在 Bash 中使用heredoc创建新文件

linux - Chef 厨房无法从 Windows 10 集成 bash 工作

bash - Linux 源代码在 .sh 文件中不起作用?