• 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];
    }
  • 相关阅读:
    Codeforces Round #368 Div. 2
    TXT文件去除多余空行
    #4247. 串
    #4322. 字符串游戏(strgame)
    #4214. 谢特
    #4155. 咱们去烧菜吧
    #4350. 「十二省联考 2019」字符串问题
    #4349. 「十二省联考 2019」异或粽子
    #4303. 跳蚤
    #4302. 魔法咒语
  • 原文地址:https://www.cnblogs.com/joesen/p/3884215.html
Copyright © 2020-2023  润新知