文件下载(nim学习系列)
文件下载(nim学习系列)
下载功能主要用于内网文件传输或者将VPS文件下载至目标机器。
http 协议下载
这里使用到 newAsyncHttpClient 函数
- 修改默认的user-agent (defUserAgent = "Nim httpclient/1.4.2")
- 显示下载进度
源代码 httpDownload.nim
编译
nim c -d:release --opt:size httpDownload.nim
使用
httpDownload.exe http://speedtest.tele2.net/10MB.zip 10MB.zip
#[
Usage: httpDownload.exe http://speedtest.tele2.net/10MB.zip 10MB.zip
Author: StudyCat
Blog: https://www.cnblogs.com/studycat
Github: https://github.com/StudyCat404
License: BSD 3-Clause
]#
import asyncdispatch, httpclient, os
proc onProgressChanged(total, progress, speed: BiggestInt) {.async.} =
echo("Downloaded ", progress, " of ", total)
echo("Current rate: ", speed div 1000, "kb/s")
proc httpDownload(url, fileName:string) {.async.} =
let ua = r"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1"
var client = newAsyncHttpClient(userAgent = ua)
client.onProgressChanged = onProgressChanged
await client.downloadFile(url, fileName)
echo "File finished downloading"
when isMainModule:
if paramCount() != 2:
echo "usage: ", paramStr(0), " url fileName"
else:
var myUrl = paramStr(1)
var myFileName = paramStr(2)
waitFor httpDownload(myUrl, myFileName)
ftp协议下载
- 显示下载进度
源代码 ftpDownload.nim
编译
nim c -d:release --opt:size httpDownload.nim
使用
ftpDownload.exe speedtest.tele2.net ftp anonymous@gmail.com 10MB.zip
#[
Usage: ftpDownload.exe speedtest.tele2.net ftp anonymous@gmail.com 10MB.zip
Author: StudyCat
Blog: https://www.cnblogs.com/studycat
Github: https://github.com/StudyCat404
License: BSD 3-Clause
]#
import asyncdispatch, asyncftpclient, os
proc onProgressChanged(total, progress: BiggestInt,
speed: float) {.async.} =
echo("Uploaded ", progress, " of ", total, " bytes")
echo("Current speed: ", speed, " kb/s")
proc ftpDownload(host, username, password, filename: string) {.async.} =
var ftp = newAsyncFtpClient(host, user = username, pass = password, progressInterval = 3000)
await ftp.connect()
echo("Connected")
let pathSplit = splitPath(filename)
let baseFilename = pathSplit.tail
await ftp.retrFile(filename, baseFilename, onProgressChanged)
echo("File finished downloading")
when isMainModule:
if paramCount() != 4:
echo "usage: ", paramStr(0), " host username password filename"
else:
var host = paramStr(1)
var username = paramStr(2)
var password = paramStr(3)
var filename = paramStr(4)
waitFor ftpDownload(host, username, password, filename)
标签:
nim
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~