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];
}
原文地址:https://www.cnblogs.com/joesen/p/3884215.html