上传图片到服务器 iis

编写客户程序将图片重新编码为可以通过http传输的格式(base code 64),调用一个web 服务端功能,服务端功能可以接收传入的数据并重新反编码为图片文件格式写入web 服务器的文件夹中。

以下示例程序将图片重新编码为Base64格式,并通过HTTP传输到服务端功能:

import requests
import base64

# 读取图片文件并编码为Base64字符串
def encode_image_to_base64(image_path):
    with open(image_path, "rb") as file:
        encoded_string = base64.b64encode(file.read()).decode("utf-8")
    return encoded_string

# 发送Base64数据到服务端功能
def send_image_to_server(encoded_image):
    url = "http://your-server-url"  # 替换为您的服务端URL
    data = {
        "image": encoded_image
    }
    response = requests.post(url, json=data)
    if response.status_code == 200:
        print("Image sent successfully.")
    else:
        print("Error while sending image:", response.content)

# 主程序
if __name__ == "__main__":
    image_path = "path/to/image.jpg"  # 替换为您的图片路径
    encoded_image = encode_image_to_base64(image_path)
    send_image_to_server(encoded_image)

在此示例中,使用Python的requests库发送HTTP POST请求到服务端功能的URL,并将Base64编码的图像作为JSON数据发送。z自己替换代码中用于服务器和图像路径的占位符。服务端应能接收POST请求,并从请求的JSON数据中提取Base64编码的图像数据。

在服务端功能中,可以使用适当的后端框架(例如Flask或Django)来解析POST请求,并将Base64编码的数据解码为图像文件。以下示例使用Flask框架来处理图像数据:

from flask import Flask, request
import base64
import os

app = Flask(__name__)

@app.route('/', methods=['POST'])
def save_image():
    image_data = request.json.get('image')
    decoded_image = base64.b64decode(image_data)
    
    # 保存图像文件到指定目录
    file_path = 'path/to/save/image.jpg'  # 替换为您想要保存图像的路径和文件名
    with open(file_path, 'wb') as file:
        file.write(decoded_image)
    
    return "Image saved successfully."

if __name__ == '__main__':
    app.run()

你可以根据实际需求进行更多的错误处理和安全增强。

客户端代码(使用Python的requests库):

import requests
import base64

def encode_image(image_path):
    with open(image_path, 'rb') as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
    return encoded_string

# 加载要发送的图像
image_path = 'path_to_your_image.jpg'
base64_image = encode_image(image_path)

# 构建请求的数据
data = {'image': base64_image}

# 发送POST请求到服务器
response = requests.post('http://your_server_url/upload', data=data)
if response.status_code == 200:
    print('图像已成功上传到服务器!')
else:
    print('出现错误,图像上传失败。')



服务端代码(使用Python的Flask框架):

from flask import Flask, request
import base64
import os

app = Flask(__name__)

@app.route('/upload', methods=['POST'])
def upload_image():
    try:
        # 获取传入的图像数据
        base64_image = request.form.get('image')

        # 解码Base64图像数据
        decoded_image = base64.b64decode(base64_image.encode('utf-8'))

        # 写入图像文件
        image_path = "./uploaded_image.jpg"
        with open(image_path, 'wb') as image_file:
            image_file.write(decoded_image)

        return "图像已成功保存到服务器!"

    except Exception as e:
        print(str(e))
        return "保存图像时出现错误。"

if __name__ == '__main__':
    app.run()