zoukankan      html  css  js  c++  java
  • ASIFormDataRequest 上传图片

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        
        [self request];
    }
    
    - (void)saveImage
    {
        NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
        [imageData writeToFile:[self GetTempPath] atomically:YES];
    }
    
    -(NSString *)GetTempPath{
        NSString *tempPath =[NSString stringWithFormat:@"%@/upload.jpg",NSTemporaryDirectory()];
        return tempPath;
    }
    
    - (void)request
    {
        NSDictionary *postDic = [[NSDictionary alloc]init];
        [postDic setValue:@"test" forKey:@"userId"];
        [postDic setValue:[self GetTempPath] forKey:@"file"];
        
        [self uploadImage:postDic];
    }
    
    - (void)uploadImage:(NSDictionary *)dic
    {
        ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:postUrl]];
        
        // 通常数据是以’application/x-www-form-urlencoded’格式发送的,如果上传了二进制数据或者文件,那么格式将自动变为‘multipart/form-data’注意要和服务器统一。
        [request addRequestHeader:@"Content-Type" value:@"multipart/form-data"];
        //超时时间
        request.timeOutSeconds = 30;
        
        //定义异步方法
        [request setDelegate:self];
        [request setRequestMethod:@"POST"];
        [request setDidFailSelector:@selector(commonRequestDidFailed:)];
        [request setDidFinishSelector:@selector(commonRequestDidSuccess:)];
        
        //post的数据
        id key, value;
        for (int i = 0; i < [dic allKeys].count; i++)
        {
            
            key = [keys objectAtIndex: i];
            value = [params objectForKey: key];
            NSLog (@"Key: %@ for value: %@", key, value);
            
            if ([key isEqualToString:@"file"]) {
                [request setFile:value forKey:key];
                [request setShouldStreamPostDataFromDisk:YES];
            }
            else
            {
                [request setPostValue:value forKey:key];
            }
            
        }
        
         [request startSynchronous];
    }
  • 相关阅读:
    CentOS(RedHat) 6.2 Samba share权限拒绝访问
    Android NDK调试C++源码(转)
    linux du命令: 显示文件、目录大小
    网络游戏的同步
    游戏开发辅助库
    Unity3D 200个插件免费分享
    C#UDP同步实例
    C#UDP(接收和发送源码)源码完整
    C#完整的通信代码(点对点,点对多,同步,异步,UDP,TCP)
    内置函数及匿名函数
  • 原文地址:https://www.cnblogs.com/joesen/p/3884215.html
Copyright © 2011-2022 走看看