通过使用libcurl POST数据和上传与下载文件

16 篇文章 0 订阅


#import "AViewController.h"

#import <curl/curl.h>

#include "Request.pb.h"


#define  POSTURL "http://192.168.1.99/xampp/test/testFile.dmg"

// #define  POSTFIELDS "email=myemail@163.com&password=mypassword&autologin=1&submit=&type="

//#define  FILENAME "/Users/chengen/Desktop/TestPro/TestPro/en.lproj/app"

staticsize_t write_data(void *buffer,size_t size,size_t nmemb,void *userp)

{

   FILE *fptr=(FILE*)userp;

   fwrite(buffer, size, nmemb, fptr);

   fflush(fptr);

   return nmemb;

}


@interface AViewController ()<UITextFieldDelegate>

{

   UITextField*textField0, *textField1, *textField2;

}


@end


@implementation AViewController


//UI界面

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

   self = [superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];

   if (self) {

        // Custom initialization

    }

    return self;

}


- (void)viewDidLoad

{

    [superviewDidLoad];

  //  UILabel*labe=[[UILabel alloc]initWithFrame:C]

   UIButton *button = [[UIButtonalloc]initWithFrame:CGRectMake(100,300,150,100)];

    

    [button setBackgroundColor:[UIColorblueColor]];

    [button setTitle:@"button"forState:UIControlStateNormal];

    [button setTitleColor:[UIColorwhiteColor]forState:UIControlStateNormal];

    [button addTarget:selfaction:@selector(buttonClicked:)forControlEvents:UIControlEventTouchUpInside];

    

    [self.viewaddSubview:button];

    

    

   UILabel *lable= [[UILabelalloc]initWithFrame:CGRectMake(15,65,70,30)];

    lable.backgroundColor=[UIColorgreenColor];

    lable.opaque =YES;

//    lable.textAlignment=UITextAlignmentLeft;

    lable.adjustsFontSizeToFitWidth=YES;

    lable.text =@"A";

    [self.viewaddSubview:lable];

    

   UILabel *lable1= [[UILabelalloc]initWithFrame:CGRectMake(15,120,70,30)];

    lable1.backgroundColor=[UIColordarkGrayColor];

    lable1.opaque =YES;

  //  lable1.textAlignment=UITextAlignmentLeft;

    lable1.adjustsFontSizeToFitWidth=YES;

    lable1.text =@"B";

    [self.viewaddSubview:lable1];

    

   UILabel *lable2= [[UILabelalloc]initWithFrame:CGRectMake(15,180,70,30)];

    lable2.backgroundColor=[UIColorblueColor];

    lable2.opaque =YES;

  //  lable2.textAlignment=UITextAlignmentLeft;

    lable2.adjustsFontSizeToFitWidth=YES;

    lable2.text =@"C";

    [self.viewaddSubview:lable2];

   

    

    textField0=[[UITextFieldalloc]initWithFrame:CGRectMake(85.0f,60.0f,190.0f,40.0f)];

    [textField0setBorderStyle:UITextBorderStyleRoundedRect];

    textField0.autocorrectionType=UITextAutocorrectionTypeNo;

    textField0.keyboardType=UIKeyboardTypeNumberPad;

    textField0.autocapitalizationType=UITextAutocapitalizationTypeNone;

    textField0.returnKeyType=UIReturnKeyDone;

    [self.viewaddSubview:textField0];

    [textField0 release];

    

    

    

    textField1=[[UITextFieldalloc]initWithFrame:CGRectMake(85.0f,120.0f,190.0f,40.0f)];

    [textField1setBorderStyle:UITextBorderStyleRoundedRect];

    textField1.autocorrectionType=UITextAutocorrectionTypeNo;

    textField1.autocapitalizationType=UITextAutocapitalizationTypeNone;

    textField1.returnKeyType=UIReturnKeyDone;

    [self.viewaddSubview:textField1];

    [textField1 release];


    textField2=[[UITextFieldalloc]initWithFrame:CGRectMake(85.0f,180.0f,190.0f,40.0f)];

    [textField2setBorderStyle:UITextBorderStyleRoundedRect];

    textField2.autocorrectionType=UITextAutocorrectionTypeNo;

    textField2.autocapitalizationType=UITextAutocapitalizationTypeNone;

    textField2.returnKeyType=UIReturnKeyDone;

    textField2.delegate =self;


    [self.viewaddSubview:textField2];

    [textField2 release];

    

// Do any additional setup after loading the view.

}


- (void)viewWillAppear:(BOOL)animated

{

    [superviewWillAppear:animated];

}



-(BOOL)textFieldShouldReturn:(UITextField*)textField

{

    [textField resignFirstResponder];

    return YES;

}



- (void)buttonClicked:(UIButton *)sender

{

  

    


   

    

    //Nstring 转换成 int cstring

   constint intstring0=[textField0.textintValue];

   constchar *cstring1=[textField1.textUTF8String];

   constint intstring2=[textField2.textintValue];


       //protobuf 序列化

   Request request;

    request.set_a(intstring0);

    request.add_b_str(cstring1);

    request.set_c(intstring2);

    

   int length=request.ByteSize();

   NSLog(@"length==%d",length);

   char* buf=newchar[length];

    request.SerializeToArray(buf, length);

   NSLog(@"buf==%s",buf);


       //protobuf 反序列化

//    request.ParsePartialFromArray(buf, length);

//    NSLog(@"request=%d,%s,%d",request.a(),request.b_str(0).data(),request.c());

//    delete [] buf;

    

    NSLog(@"-------POST---------");

     //沙箱机制

    

    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

    NSLog(@"Get document path:%@",[pathsobjectAtIndex:0]);

   NSString *fileName=[[pathsobjectAtIndex:0]

                        stringByAppendingPathComponent:@"myFiles1"];

    constchar* cfilename = [fileNamecStringUsingEncoding:NSUTF8StringEncoding];


   //上传和下载文件

   CURL *curl;

   CURLcode res;

       

   FILE *fptr;

   structcurl_slist *http_head=NULL;

    

    #define FILENAME cfilename

    

   if ((fptr=fopen(FILENAME,"w")) ==NULL) {

        fprintf(stderr,"fopen file error: %s\n",FILENAME);

       exit(1);

    }

    

   fseek(fptr,0L,2);

   unsignedlong filesize =ftell(fptr);

   NSLog(@"filesize == %d", (int)filesize);


//以下注释部门取消就是上传文件

    curl=curl_easy_init();

    curl_easy_setopt(curl,CURLOPT_URL,POSTURL); // 地址

//    curl_easy_setopt(curl, CURLOPT_POSTFIELDS,buf);  //参数

    curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,write_data);//对返回的数据进行操作的函数地址

    curl_easy_setopt(curl,CURLOPT_WRITEDATA,fptr);  //设置WRITEFUNCTION的第四个参数值

//    curl_easy_setopt(curl, CURLOPT_POST,1);//设置为非0,则表示本次操作为post

//    curl_easy_setopt(curl, CURLOPT_VERBOSE,1); //设置为非0在执行时打印请求信息

//    curl_easy_setopt(curl, CURLOPT_HEADER,1);  //设置为非0将响应体一起传给WRITEFUNCTION

//    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION,1); //设置为非0,响应tou信息Location

//    curl_easy_setopt(curl, CURLOPT_COOKIEFILE,"/Users/chengen/Desktop/helloworld");//设置对应的COOKIEFILE路径,该路径文件并不一定需要在物理磁盘上实际存在

    res=curl_easy_perform(curl);

   NSLog(@"%d", res);

    curl_easy_cleanup(curl);

    

    //下载文件的大小

    

   fseek(fptr,0L,2);

   unsignedlong filesize1 =ftell(fptr);

   NSLog(@"filesize1== %d", (int)filesize1);

    

}


- (void)didReceiveMemoryWarning

{

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end



运行程序后得到这样的一个界面:



在界面的A,B,C中输入protocbuf 消息的数据

点击界面上的button触发响应。

实现这个上传下载还须下载一个XAMPP Control的东西

下载后至今运行就可以了

得到这个一个窗口:


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用libcurl库进行POST方法上传文件的步骤如下: 1. 初始化curl库:`curl_global_init(CURL_GLOBAL_ALL);` 2. 创建curl句柄:`CURL* curl = curl_easy_init();` 3. 设置请求URL:`curl_easy_setopt(curl, CURLOPT_URL, url);` 4. 设置请求方式为POST:`curl_easy_setopt(curl, CURLOPT_POST, 1L);` 5. 设置上传文件:`curl_easy_setopt(curl, CURLOPT_READDATA, file);` 其中,`file`为你要上传文件文件指针。 6. 设置上传文件大小:`curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, file_size);` 其中,`file_size`为你要上传文件的大小。 7. 设置上传文件名:`curl_easy_setopt(curl, CURLOPT_POSTFIELDS, file_name);` 其中,`file_name`为你要上传文件文件名。 8. 执行请求:`curl_easy_perform(curl);` 9. 清理curl句柄:`curl_easy_cleanup(curl);` 完整的示例代码如下: ``` #include <stdio.h> #include <curl/curl.h> int main(void) { CURL *curl; CURLcode res; FILE *file; const char *url = "http://example.com/upload.php"; const char *file_name = "example.txt"; long file_size; file = fopen(file_name, "rb"); if (!file) { fprintf(stderr, "Failed to open file '%s'\n", file_name); return 1; } fseek(file, 0L, SEEK_END); file_size = ftell(file); rewind(file); curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_POST, 1L); curl_easy_setopt(curl, CURLOPT_READDATA, file); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, file_size); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, file_name); res = curl_easy_perform(curl); if (res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); curl_easy_cleanup(curl); } fclose(file); curl_global_cleanup(); return 0; } ``` 注意,这只是一个简单的示例,实际应用中还需要添加错误处理和其他必要的选项。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值