码迷,mamicode.com
首页 > 其他好文 > 详细

ASIFormDataRequest 上传图片

时间:2014-08-01 10:27:41      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   文件   数据   for   

- (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];
}

 

ASIFormDataRequest 上传图片,布布扣,bubuko.com

ASIFormDataRequest 上传图片

标签:style   blog   color   os   io   文件   数据   for   

原文地址:http://www.cnblogs.com/joesen/p/3884215.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!