curl进行文件上传的一个demo

/* ftpupload.c */
#include <stdio.h>
#include <string.h>

#include <curl/curl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#ifdef WIN32
#include <io.h>
#else
#include <unistd.h>
#endif

#include <stdlib.h>
#include <string.h>
#include <time.h>
#if !defined(_WIN32_WCE)
#include <sys/timeb.h>
#endif

/*
 * This example shows an FTP upload, with a rename of the file just after
 * a successful upload.
 *
 * Example based on source code provided by Erick Nuwendam. Thanks!
 */

/* NOTE: if you want this example to work on Windows with libcurl as a
   DLL, you MUST also provide a read callback with CURLOPT_READFUNCTION.
   Failing to do so will give you a crash since a DLL may not use the
   variable's memory when passed in to it from an app like this. */
/* 上传数据读取的回调函数 */
static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream)
{
	curl_off_t nread;
	/* in real-world cases, this would probably get this data differently
	as this fread() stuff is exactly what the library already would do
	by default internally */
	size_t retcode = fread(ptr, size, nmemb, stream);

	nread = (curl_off_t)retcode;

	fprintf(stderr, "*** We read %" CURL_FORMAT_CURL_OFF_T " bytes from file\n", nread);

	return retcode;
}

/* debug输出之回调函数 */
int debugFun(CURL* curl, curl_infotype type, char* str, size_t len, void* stream)  
{  
	//只打印CURLINFO_TEXT类型的信息  
	if(type == CURLINFO_TEXT)  
	{  
		fwrite(str, 1, len, (FILE*)stream);  
	}  
}  

static char	sMillTime[17+1];
char *GetMillTime()
{
	struct tm *t;
	struct timeb mtp;

	ftime(&mtp);
	memset(sMillTime,0x00,sizeof(sMillTime));
	t = localtime(&mtp.time);
	sprintf(sMillTime,"%4d%02d%02d%02d%02d%02d%03d",
		t->tm_year+1900,t->tm_mon+1,t->tm_mday,
		t->tm_hour, t->tm_min, t->tm_sec,mtp.millitm);
	return sMillTime;
}

int main(int argc, char*argv[])
{
	CURL *curl;
	CURLcode res;
	FILE *fpSendFile = NULL, *fpDebugFile = NULL;
	struct stat file_info;
	curl_off_t fsize;

	char *pLocalFile = NULL;
	char remoteUrl[1024] = {0};
	char *destFileName = NULL;
	char *userpasswd = NULL;

	struct curl_slist *headerlist=NULL;
	char buf_1[1024] = {0};
	char buf_2[1024] = {0};

	if(argc<5)
	{
		char *pExeName = strrchr(argv[0], '/');

		printf("Usage:\n\t%s localfile remoteurl destfilename [user:passwd]\n", pExeName?(pExeName+1):argv[0]);
		printf("\n\t%s /tmp/testfile.txt ftp://example.com testfile.txt [user1:123456]\n", pExeName?(pExeName+1):argv[0]);
		printf("\n\t%s /tmp/testfile.txt ftp://example.com/dir1/dir2 testfile.txt [user1:123456]\n", pExeName?(pExeName+1):argv[0]);

		exit(1);
	}

	/* 本地文件 */
	pLocalFile = argv[1];
	/* 目标文件名 */
	destFileName = argv[3];
	/* 目标URL */
	sprintf(remoteUrl, "%s/%s.ftp!", argv[2], destFileName);	/* 传输过程临时文件名,以.ftp!为后缀 */
	//sprintf(remoteUrl,"%s/%s",argv[2],destFileName);
	/* 用户密码,非匿名用户时使用 */
	userpasswd = argv[4];

	/* 上传后续指令集 */
	/* rename from 指令 */
	sprintf(buf_1,"RNFR %s.ftp!",destFileName);
	//sprintf(buf_1,"RNFR %s",destFileName);
	/* rename to 指令 */
	sprintf(buf_2,"RNTO %s",destFileName);	/* 从传输临时文件名还原成最终文件名 */

	/* get the file size of the local file */
	if(stat(pLocalFile, &file_info)) {
		printf("Couldnt open '%s': %s\n", pLocalFile, strerror(errno));
		return 1;
	}
	fsize = (curl_off_t)file_info.st_size;
	printf("Local file size: %" CURL_FORMAT_CURL_OFF_T " bytes.\n", fsize);

	//将相关的调试信息打印到ftpDebugFile.out中  
	if(NULL == (fpDebugFile = fopen("ftpDebugFile.out", "a+")))  
		return -1;  

	/* get a FILE * of the same file */
	fpSendFile = fopen(pLocalFile, "rb");

	/* In windows, this will init the winsock stuff */
	curl_global_init(CURL_GLOBAL_ALL);

	/* get a curl handle */
	curl = curl_easy_init();
	if(curl) {
		/* now specify which file to upload,设置上传文件句柄 */
		curl_easy_setopt(curl, CURLOPT_READDATA, fpSendFile);
		/* we want to use our own read function 数据读取回调函数,16K字节规格读取*/
		curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);

		/* enable uploading */
		curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);

		/* specify target */
		curl_easy_setopt(curl,CURLOPT_URL, remoteUrl);

		/* 是否自动创建目标目录 */
		curl_easy_setopt(curl, CURLOPT_FTP_CREATE_MISSING_DIRS, 1);

		/* Set the size of the file to upload (optional).  If you give a *_LARGE
		option you MUST make sure that the type of the passed-in argument is a
		curl_off_t. If you use CURLOPT_INFILESIZE (without _LARGE) you must
		make sure that to pass in a type 'long' argument. */
		curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)fsize);

		/* 上传完成后的附加处理动作:文件名从传输临时名字还原成最终名字 */
		/* build a list of commands to pass to libcurl */
		headerlist = curl_slist_append(headerlist, buf_1);
		headerlist = curl_slist_append(headerlist, buf_2);
		/* pass in that last of FTP commands to run after the transfer */
		curl_easy_setopt(curl, CURLOPT_POSTQUOTE, headerlist);

		/* Switch on full protocol/debug output */
		curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

		/* debug日志输出opt 设置debug输出文件指针 */
		curl_easy_setopt(curl, CURLOPT_DEBUGDATA, fpDebugFile);
		/* debug日志callback函数 
		curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, debugFun);*/

		/* 设置用户密码,非匿名用户的认证时使用 */
		curl_easy_setopt(curl, CURLOPT_USERPWD, userpasswd); 

		/* Now run off and do what you've been told! */
		res = curl_easy_perform(curl);
		/* Check for errors */
		if(res != CURLE_OK)
			fprintf(stderr, "curl_easy_perform() failed: [%d] %s\n", res, curl_easy_strerror(res));
		else
			fprintf(stdout, "curl_easy_perform() ok \n");

		/* clean up the FTP commands list */
		curl_slist_free_all (headerlist);

		/* always cleanup */
		curl_easy_cleanup(curl);
	}

	fclose(fpSendFile); /* close the local file */

	curl_global_cleanup();

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pony12

助力1000篇OpenDDS文

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值