You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用find&curl上传含特殊字符文件至FTP时的URL编码问题

FTP上传保留目录结构时含特殊字符文件报错解决

使用场景

同一WiFi下,通过安卓设备的类Ubuntu终端,用curl将手机数据上传到笔记本的Python FTP服务器,要求保留目录结构,后续在笔记本处理文件。

待上传的文件/目录结构示例

dir1
  |--1.mp3
  |--dir2
       |--download  1.jpg
       |--download (2).jpg

复现步骤

  1. 笔记本运行Python FTP服务器,安卓端执行命令:

    find dir1 -type f -exec curl -u ftp:ftp --ftp-create-dirs -T {} ftp://192.168.x.x/ \;
    

    该命令可正常上传,但所有文件都存入FTP根目录,无法保留目录结构。

  2. 为保留子目录结构,修改命令如下:

    find dir1 -type f -exec curl -u ftp:ftp --ftp-create-dirs -T {} ftp://192.168.x.x/{} \;
    

    此时含空格、括号等特殊字符的文件(如download 1.jpg、download (2).jpg)报错:

    curl: (3) URL using bad/illegal format or missing URL
    

已尝试操作

尝试仅替换空格为%20的命令:

find dir1 -type f -exec bash -c 'y=$(echo "$1"); fname=$(echo $y | sed "s/ /%20/g"); echo $y;echo $fname;echo ""; curl -u ftp:ftp --ftp-create-dirs -T $y ftp://192.168.x.x/$fname' bash {} \;

结果仅处理空格无效,含括号的文件仍报URL格式错误;尝试--data-urlencoding参数,无法与-T(上传)搭配,且会添加?符号,不符合需求。

解决方案

需要对文件路径中的所有URL特殊字符(包括空格、括号、引号等)进行完整编码,可通过以下两种方法实现:

方法1:自定义URL编码函数

find dir1 -type f -exec bash -c '
urlencode() {
  local string="$1"
  local encoded=""
  local i c
  for ((i=0; i<${#string}; i++)); do
    c=${string:i:1}
    case "$c" in
      [a-zA-Z0-9_.~-]) encoded+="$c" ;;
      *) encoded+=$(printf "%%%02X" "'$c") ;;
    esac
  done
  echo "$encoded"
}
file_path="$1"
encoded_path=$(urlencode "$file_path")
curl -u ftp:ftp --ftp-create-dirs -T "$file_path" "ftp://192.168.x.x/$encoded_path"
' bash {} \;

方法2:借助printf简化编码

find dir1 -type f -exec bash -c '
file_path="$1"
encoded_path=$(printf "%s" "$file_path" | sed "s/[^a-zA-Z0-9_.~-]/$(printf "%%%02X" "\0")/g")
curl -u ftp:ftp --ftp-create-dirs -T "$file_path" "ftp://192.168.x.x/$encoded_path"
' bash {} \;

说明

  • 两种方法都会对路径中的非安全URL字符进行标准编码,避免curl识别URL时出错;
  • 变量外层加双引号,防止空格导致路径被拆分。

内容的提问来源于stack exchange,提问作者iamsmith41

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 16:24:52