JumpKick.HttpLib — 파일 다운로드 DownloadTo
설명
.DownloadTo(저장 경로, ...) 를 사용해 네트워크 리소스를 로컬 디스크에 직접 저장합니다. 보통 Http.Get() 와 함께 사용합니다.
콜백 매개변수:
onProgressChanged:(bytesCopied, totalBytes?)bytesCopied:다운로드 완료된 바이트 수totalBytes:파일 전체 바이트 수, 널 허용 타입(long?)
서버에서Content‑Length응답 헤더를 내려주지 않으면totalBytes.HasValue == false이며 다운로드 퍼센트를 계산할 수 없고 다운로드된 바이트만 출력할 수 있습니다.
onSuccess:(headers)
다운로드 완료 콜백, 응답 헤더 정보를 얻을 수 있습니다.
예시
진행률 및 완료 콜백 포함
using System;
using JumpKick.HttpLib;
class Program
{
static void Main(string[] args)
{
string url = "https://codelexample.test/file.zip";
string savePath = @"E:\httplib.zip";
Http.Get(url)
.DownloadTo(
savePath,
onProgressChanged: (bytesCopied, totalBytes) =>
{
if (totalBytes.HasValue)
{
// *1.0d 로 부동 소수점 연산 강제, 정수 나눗셈이 0이 되는 현상 방지
double progress = (bytesCopied / totalBytes.Value * 1.0d) * 100;
Console.WriteLine($"다운로드 진행률:{progress:F2} %");
}
Console.WriteLine($"다운로드된 바이트:{bytesCopied} bytes");
},
onSuccess: (headers) =>
{
Console.WriteLine("\n파일 다운로드 완료");
}
)
.OnFail(ex =>
{
Console.WriteLine("다운로드 오류:" + ex.Message);
})
.Go();
Console.ReadKey();
}
}Code language: JavaScript (javascript)
예시‑최소 다운로드
진행률 감시 없음
using System;
using JumpKick.HttpLib;
class Program
{
static void Main(string[] args)
{
Http.Get("https://httpbin.org/image/png")
.DownloadTo(@"E:\test.png",
onSuccess: headers =>
{
Console.WriteLine("다운로드 완료");
})
.OnFail(ex => Console.WriteLine(ex.Message))
.Go();
Console.ReadKey();
}
}Code language: JavaScript (javascript)
예외 테스트
존재하지 않는 리소스 주소를 입력해 404 오류 포착
using System;
using JumpKick.HttpLib;
class Program
{
static void Main(string[] args)
{
// 유효하지 않은 링크, 404 발생
Http.Get("https://httpbin.org/notfoundfile")
.DownloadTo(@"E:\error.png",
onProgressChanged: (bytesCopied, totalBytes) =>
{
Console.WriteLine($"다운로드됨:{bytesCopied} bytes");
},
onSuccess: headers =>
{
Console.WriteLine("다운로드 완료");
})
.OnFail(ex =>
{
Console.WriteLine("예외 포착:" + ex.Message);
})
.Go();
Console.ReadKey();
}
}Code language: JavaScript (javascript)
요약
| 기능 | API | 핵심 메서드 |
|---|---|---|
| GET 요청 | Http.Get(url) | 기본 쿼리, 파일 다운로드 .DownloadTo() |
| POST 폼 | Http.Post(url) | .Form() 폼 키‑값 쌍 |
| POST JSON | Http.Post(url) | .Body(문자열,미디어타입) |
| 파일 업로드 | Http.Post(url) | .Upload() + NamedFileStream |
파일 다운로드 DownloadTo
Previous: 파일 업로드 Upload