昌江县纤凝网

VScode使用sftp上传本地文件到服务器端

2026-03-30 07:34:01 浏览次数:1
详细信息

方法一:使用 SFTP 插件(推荐)

1. 安装插件

2. 配置 SFTP

步骤: 在项目根目录按 Ctrl+Shift+P,输入 SFTP: Config,选择配置文件 在生成的 sftp.json 文件中配置:
{
    "name": "My Server",
    "host": "your-server-ip",
    "protocol": "sftp",
    "port": 22,
    "username": "your-username",
    "password": "your-password",  // 可选,建议使用私钥
    "privateKeyPath": "C:/Users/username/.ssh/id_rsa",  // Windows路径
    // "privateKeyPath": "/Users/username/.ssh/id_rsa",  // Mac路径
    // "privateKeyPath": "/home/username/.ssh/id_rsa",   // Linux路径
    "passphrase": "your-passphrase",  // 如果私钥有密码
    "ignore": [
        "**/.vscode/**",
        "**/.git/**",
        "**/node_modules/**",
        "*.log"
    ],
    "remotePath": "/home/username/project",  // 服务器上的路径
    "uploadOnSave": true,  // 保存时自动上传
    "syncMode": "update",  // 只上传修改的文件
    "watcher": {  // 监听文件变化
        "files": "**/*",
        "autoUpload": true,
        "autoDelete": true
    }
}

3. 使用方式

手动上传单个文件: 上传文件夹: 同步整个项目: 下载服务器文件:

方法二:使用 Remote - SSH 插件

1. 安装 Remote - SSH 扩展

2. 配置连接

点击左侧活动栏的远程资源管理器图标 点击齿轮图标配置 SSH Hosts 在 ~/.ssh/config 文件中添加:
Host myserver
    HostName your-server-ip
    User your-username
    Port 22
    IdentityFile ~/.ssh/id_rsa
在远程资源管理器中连接服务器

3. 文件操作

连接后:

方法三:命令行方式(备用)

使用 scp 命令:

# 上传单个文件
scp localfile.txt username@server:/remote/path/

# 上传文件夹(递归)
scp -r localfolder username@server:/remote/path/

# 使用指定端口
scp -P 2222 localfile username@server:/path/

使用 sftp 命令:

sftp username@server
put localfile /remote/path/
put -r localfolder /remote/path/

实用技巧

1. 使用密钥认证(更安全)

{
    "privateKeyPath": "~/.ssh/id_rsa",
    "passphrase": "your-passphrase"
}

2. 排除不需要上传的文件

{
    "ignore": [
        ".git/",
        ".vscode/",
        "node_modules/",
        "*.log",
        ".env"
    ]
}

3. 配置文件组

{
    "profiles": {
        "production": {
            "host": "prod-server",
            "remotePath": "/var/www/prod"
        },
        "staging": {
            "host": "staging-server",
            "remotePath": "/var/www/staging"
        }
    }
}

4. 自动上传配置

{
    "uploadOnSave": true,
    "watcher": {
        "files": "**/*",
        "autoUpload": true,
        "autoDelete": true
    }
}

常见问题解决

1. 连接失败

2. 权限问题

3. 中文乱码

{
    "encoding": "utf8"
}

4. 排除 .gitignore 文件

{
    "ignore": ".gitignore"
}

推荐组合

开发时:使用 SFTP 插件的 uploadOnSave 功能 批量上传:使用 Sync Local -> Remote 复杂操作:使用 Remote - SSH 直接编辑远程文件

选择哪种方式取决于你的具体需求:

相关推荐