c++ - FTP文件上传

标签 c++ ftp

BOOL uploadFile(char *filename, char *destination_name, char *address, char *username, char *password)
{
    BOOL t = false;
    HINTERNET hint, hftp;
    hint = InternetOpen("FTP", INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, INTERNET_FLAG_ASYNC);
    hftp = InternetConnect(hint, address, INTERNET_DEFAULT_FTP_PORT, username, password, INTERNET_SERVICE_FTP, 0 , 0);
    t = FtpPutFile(hftp, filename, destination_name, FTP_TRANSFER_TYPE_BINARY, 0);
    InternetCloseHandle(hftp);
    InternetCloseHandle(hint);
    return t;
}

这是我上传文件到服务器的功能,写的好吗? 我在函数中使用

uploadFile(workFullPath,extractFilename(workFullPath),"address","login","password");

但是我的文件没有出现在 ftp 上。

最佳答案

您根本没有进行任何错误处理,因此您无法知道文件未上传的原因。

每当 WinInet 功能失败时,您可以调用 GetLastError()根据每个函数的 WinInet 文档找出它失败的原因。

如果 GetLastError() 返回 ERROR_INTERNET_EXTENDED_ERROR , 使用 InternetGetLastResponseInfo()获取服务器的错误:

ERROR_INTERNET_EXTENDED_ERROR
12003
An extended error was returned from the server. This is typically a string or buffer containing a verbose error message. Call InternetGetLastResponseInfo to retrieve the error text.

参见 WinInet 的 Handling Errors使用 InternetGetLastResponseInfo() 示例的文档。

其他需要注意的事情 - 您正在使用 INTERNET_FLAG_ASYNC 标志调用 InternetOpen():

Makes only asynchronous requests on handles descended from the handle returned from this function.

但是,您实际上并没有异步使用 WinInet,因此您根本不应该使用该标志。

参见 WinInet 的 FTP Sessions有关如何使用 WinInet FTP 功能的更多详细信息的文档。

尝试更像这样的东西:

BOOL uploadFile(char *filename, char *destination_name, char *address, char *username, char *password)
{
    BOOL res = FALSE;
    DWORD err;

    HINTERNET hint = InternetOpen("FTP", INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0);
    if (hint == NULL)
    {
        err = GetLastError();
        // handle the error as needed...
        goto done;
    }

    HINTERNET hftp = InternetConnect(hint, address, INTERNET_DEFAULT_FTP_PORT, username, password, INTERNET_SERVICE_FTP, 0 , 0);
    if (hftp == NULL)
    {
        err = GetLastError();
        // handle the error as needed...
        goto cleanup;
    }

    res = FtpPutFile(hftp, filename, destination_name, FTP_TRANSFER_TYPE_BINARY, 0);
    if (!res)
    {
        err = GetLastError();
        // handle the error as needed...
    }

cleanup:
    if (hftp) InternetCloseHandle(hftp);
    if (hint) InternetCloseHandle(hint);

done:
    return res;
}

关于c++ - FTP文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44530788/

相关文章:

c++ - 检查模板函数的数据类型

java - 多线程 FTP 输入流的输出不一致

powershell - 如何在Windows 2019中将FTP服务器的SSL设置为无SSL

mercurial - 从 BitBucket 存储库自动部署文件

java - 如何用java在内存中存储文件?

c# - 调用 FtpClient 一次以递归列出目录

c++ - 我无法使用 premake5 添加额外的库

c++ - 如何测试分配器是否使用 std::allocate 进行内存分配?

c++ - 如何正确使用boost::variant?

c++ - 如何通过strtok忽略一个字符?