我不能上传文件到FTP服务器

C++ I cant upload file to FTP server

本文关键字:FTP 服务器 文件 不能      更新时间:2023-10-16

我想上传一个文件到我的FTP服务器使用c++代码,我能够FTP我的服务器与FileZilla。

当我运行我的c++代码时,它抛出一个输出"3"错误(GetLastError()函数将此值返回给ftppputfile()函数

#pragma comment (lib,"wininet.lib")
#include <windows.h>
#include <wininet.h> //for uploadFile function
#include <iostream>
using namespace std;
int main()
{
    HINTERNET hint, hftp;
    hint = InternetOpen("FTP", INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, INTERNET_FLAG_ASYNC);
    hftp = InternetConnect(hint, "MY IP ADRESS", INTERNET_DEFAULT_FTP_PORT, "MY NAME", "MY PASS", INTERNET_SERVICE_FTP, 0, 0);
    if (!FtpPutFile(hftp, "C://Users//Elliot//Desktop//log.txt", "//log.txt", FTP_TRANSFER_TYPE_BINARY, 0))
    {
        cout << "FAIL !" << endl;
        cout << GetLastError() << endl;
    }
    else {
        cout << "file sended !";
    };
    InternetCloseHandle(hftp);
    InternetCloseHandle(hint);
    system("PAUSE");
}

我尝试过的事情:

  • 更改服务器(我创建了新服务器,但结果仍然相同)

  • 控制防火墙
  • 以管理员身份运行

  • 断点(ftppputfile给出错误)

错误信息很清楚。文件不在那里,就没有什么可发送的。在继续使用互联网功能之前,您可以使用std::ifstream轻松检查文件的路径。

使用FtpSetCurrentDirectory设置目标目录。在这个例子中,我使用"public_html",也许你的服务器是不同的。

#include <windows.h>
#include <wininet.h> 
#include <iostream>
#include <string>
#include <fstream>
#pragma comment (lib,"wininet.lib")
using namespace std;
int main()
{
    string file = "C:\path.txt";
    string site = "www.site.com";
    string user = "username";
    string pass = "password";
    if (!ifstream(file))
    {
        cout << "no filen";
        return 0;
    }
    HINTERNET hint = InternetOpen(0, INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0);
    HINTERNET hftp = InternetConnect(hint, site.c_str(), INTERNET_DEFAULT_FTP_PORT,
        user.c_str(), pass.c_str(), INTERNET_SERVICE_FTP, 0, 0);
    if (FtpSetCurrentDirectory(hftp, "public_html"))
    {
        if (!FtpPutFile(hftp, file.c_str(), "log.txt", FTP_TRANSFER_TYPE_BINARY, 0))
        {
            cout << "FAIL!" << endl;
            cout << GetLastError() << endl;
        }
        else
        {
            cout << "file sended !";
        }
    }
    InternetCloseHandle(hftp);
    InternetCloseHandle(hint);
    return 0;
}