从 C++ 上的网址下载文件

Download file from url on C++

本文关键字:下载 文件 C++      更新时间:2023-10-16

我有C++代码应该从URL下载文件并将其保存在某个目录中。我实现了这个。但是我不知道如何实现服务器端。下载文件
C++代码的网址

string dwnld_URL = "127.0.0.1/screenchote.png";
string savepath = "D:\screenchote.png";
URLDownloadToFile(NULL, dwnld_URL.c_str(), savepath.c_str(), 0, NULL);

dwnload_URl = 我们必须下载文件的网址

保存路径 = 将文件保存在路径中

如何做服务器端?

这很有帮助,但它需要一些发展和改进:

#include<tchar.h>
#include<urlmon.h>
#pragma comment (lib,"urlmon.lib")
int main ()
{
HRESULT hr=Urldownloadtofile( NULL, _T("your web page"), _T("c:/web_page.html") 0, NULL );
return 0;
}

HRESULT hr = Urldownloadtofile( NULL, L"your web page", L"c:/web_page.html", 0, NULL );

简单地说,你可以使用URLDownloadToFile((函数从互联网上下载任何内容,如/files等。

如果要将 URL 和文件路径作为变量传递,请使用此方法

#include <iostream>
#include<Windows.h>
#include<string>
#pragma comment(lib, "urlmon.lib")
using namespace std;
int main()
{
// URL & FILE PATH IN STRING
string FilePath = "D:testimage.png";
string URL = "https://cdn.pixabay.com/photo/2015/12/01/20/28/road-1072823__340.jpg"; 

wstring tempUrl = wstring(URL.begin(), URL.end());
wstring tempPath = wstring(FilePath.begin(), FilePath.end());
// Applying c_str() method on temp
LPCWSTR wideStringUrl = tempUrl.c_str();
LPCWSTR wideStringPath = tempPath.c_str();
// URL must include the HTTPS/HTTP.
if (S_OK == URLDownloadToFile(NULL, wideStringUrl, wideStringPath, 0, NULL)) {
cout << "Downlod: Succses" << endl;
} else {
cout << "Download: Fails" << endl;
}
return 0;
}

URL 必须包含 HTTPS/HTTP。

如果要直接传递 URL 和保存路径:

#include <iostream>
#include<Windows.h>
#include<string>
#pragma comment(lib, "urlmon.lib")
using namespace std;
int main()
{
if (S_OK == URLDownloadToFile(NULL, L"https://cdn.pixabay.com/photo/2015/12/01/20/28/road-1072823__340.jpg", L"D:testimage.png", 0, NULL)) {
cout << "Downlod: Succses" << endl;
} else {
cout << "Download: Fails" << endl;
}
return 0;
}

文件 PATH= 要保存内容的文件的路径。

URL= 它是您要下载的网站的地址,例如,图像或文本文件的网址

> -> URLDownloadToFile((