fdfs_upload_file发送内存文件
这里只对fdfs_upload_file进行改造,至于其他的也是一样的原理:
在进行fdfs_upload_file的时候,如果是程序中需要实现这个功能,一种方法是使用子进程的逻辑直接调用该程序,这种处理方式需要一个临时文件,而且还需要进程的创建销毁。
另外一种思路是直接参考fdfs_upload_file源码去直接上传文件,fdfs本身就提供了一种直接上传内存缓冲的接口,对fdfs_upload_file.c源码稍加改造就可以直接使用源码实现上传文件的功能:
/**
* Copyright (C) 2008 Happy Fish / YuQing
*
* FastDFS may be copied only under the terms of the GNU General
* Public License V3, which may be found in the FastDFS source kit.
* Please visit the FastDFS Home Page http://www.fastken.com/ for more detail.
**/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "fdfs_client.h"
#include "fdfs_global.h"
#include "fastcommon/base64.h"
#include "fastcommon/sockopt.h"
#include "fastcommon/logger.h"
#include "fdfs_http_shared.h"
#include <unistd.h>
/**
* @brief
* @param fileName 文件名称
* @param confFileName client配置路径
* @param fileSize 文件内容大小
* @param buf 文件内容内存缓冲区
* @return int
*/
int fdfs_upload_file(char* fileName, char* confFileName, int fileSize, char* buf)
{
char *conf_filename;
char *local_filename;
char group_name[FDFS_GROUP_NAME_MAX_LEN + 1];
ConnectionInfo *pTrackerServer;
int result;
int store_path_index;
ConnectionInfo storageServer;
char file_id[128];
log_init();
g_log_context.log_level = LOG_ERR;
ignore_signal_pipe();
conf_filename = confFileName;
if ((result=fdfs_client_init(conf_filename)) != 0)
{
return result;
}
pTrackerServer = tracker_get_connection();
if (pTrackerServer == NULL)
{
fdfs_client_destroy();
return errno != 0 ? errno : ECONNREFUSED;
}
local_filename = fileName;
*group_name = '\0';
if ((result=tracker_query_storage_store(pTrackerServer, \
&storageServer, group_name, &store_path_index)) != 0)
{
fdfs_client_destroy();
fprintf(stderr, "tracker_query_storage fail, " \
"error no: %d, error info: %s\n", \
result, STRERROR(result));
return result;
}
const char *file_ext_name = fdfs_get_file_ext_name(local_filename);
result = storage_upload_by_filebuff1(pTrackerServer, \
&storageServer, store_path_index, \
buf, fileSize, file_ext_name, \
NULL, 0, group_name, file_id);
// 开始上传文件
// result = storage_upload_by_filename1(pTrackerServer, \
// &storageServer, store_path_index, \
// local_filename, NULL, \
// NULL, 0, group_name, file_id);
if (result == 0)
{
printf("%s\n", file_id);
}
else
{
fprintf(stderr, "upload file fail, " \
"error no: %d, error info: %s\n", \
result, STRERROR(result));
}
tracker_close_connection_ex(pTrackerServer, true);
fdfs_client_destroy();
return result;
}
int main(int argc, char *argv[])
{
char *fileName = "/home/i/images/p4.jpg";
int fd = open(fileName, O_RDONLY);
struct stat buf;
fstat(fd, &buf);
int size = buf.st_size;
char *fileContent = malloc(size);
read(fd, fileContent, size);
close(fd);
return fdfs_upload_file(fileName, "/etc/fdfs/client.conf", size, fileContent);
}

浙公网安备 33010602011771号