面试题答案
一键面试#!/bin/bash
# 本地目录
local_dir="/path/to/local/directory"
# 日志文件路径
log_file="upload_download.log"
# 文件存储服务上传API
upload_api="http://api.storage.com/upload"
# 文件存储服务下载API
download_api="http://api.storage.com/download"
# 函数:记录日志
log_error() {
local error_code=$1
local error_time=$(date +%Y-%m-%d\ %H:%M:%S)
local file_name=$2
echo "[ERROR] $error_time - HTTP Error $error_code - File: $file_name" >> $log_file
}
# 上传文件
for file in $local_dir/*; do
if [ -f "$file" ]; then
file_name=$(basename "$file")
response=$(curl -s -o /dev/null -w "%{http_code}" -X POST -T "$file" $upload_api)
if [ "$response" -ne 200 ]; then
log_error $response $file_name
continue
fi
echo "Uploaded $file_name successfully"
fi
done
# 下载文件并校验md5sum
for file in $local_dir/*; do
if [ -f "$file" ]; then
file_name=$(basename "$file")
local_md5=$(md5sum "$file" | awk '{print $1}')
temp_file=$(mktemp)
response=$(curl -s -o $temp_file -w "%{http_code}" $download_api?filename=$file_name)
if [ "$response" -ne 200 ]; then
log_error $response $file_name
rm -f $temp_file
continue
fi
downloaded_md5=$(md5sum $temp_file | awk '{print $1}')
if [ "$local_md5" = "$downloaded_md5" ]; then
echo "Downloaded $file_name successfully and md5sum matches"
else
echo "Downloaded $file_name but md5sum does not match"
fi
rm -f $temp_file
fi
done