iOS文件上传

jopen 11年前

在ios里来上传文件的方法很多,比如把文件base64直接post,本来打算这样做的,发现各种不爽,服务端收起来也各种不爽,所以干脆用标准的http上传协议mutipart来搞个上传就好,具体代码如下

头文件

    @interface HttpRequest : NSObject                +(id)upload:(NSString *)url widthParams:(NSDictionary *)params;                @end                @interface FileDetail : NSObject        @property(strong,nonatomic) NSString *name;        @property(strong,nonatomic) NSData *data;        +(FileDetail *)fileWithName:(NSString *)name data:(NSData *)data;        @end  

main文件
</div> </div>
    //        //  HttpRequest.m        //  recofm        //        //  Created by reco on 13-12-25.        //  Copyright (c) 2013年 reco. All rights reserved.        //                #import "HttpRequest.h"                        #define BOUNDARY @"----------cH2gL6ei4Ef1KM7cH2KM7ae0ei4gL6"                @implementation HttpRequest                +(id)upload:(NSString *)url widthParams:(NSDictionary *)params {                        NSError *err = nil;            NSMutableURLRequest *myRequest = [ [NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:0];            [myRequest setHTTPMethod:@"POST"];            [myRequest setValue:[@"multipart/form-data; boundary=" stringByAppendingString:BOUNDARY] forHTTPHeaderField:@"Content-Type"];                        NSMutableData *body = [NSMutableData data];                        for(NSString *key in params) {                id content = [params objectForKey:key];                if ([content isKindOfClass:[NSString class]] || [content isKindOfClass:[NSNumber class]]) {                    NSString *param = [NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n",BOUNDARY,key,content,nil];                    [body appendData:[param dataUsingEncoding:NSUTF8StringEncoding]];                                    } else if([content isKindOfClass:[FileDetail class]]) {                                        FileDetail *file = (FileDetail *)content;                                        NSString *param = [NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\";filename=\"%@\"\r\nContent-Type: application/octet-stream\r\n\r\n",BOUNDARY,key,file.name,nil];                    [body appendData:[param dataUsingEncoding:NSUTF8StringEncoding]];                    [body appendData:file.data];                    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];                }            }            NSString *endString = [NSString stringWithFormat:@"--%@--",BOUNDARY];            [body appendData:[endString dataUsingEncoding:NSUTF8StringEncoding]];            [myRequest setHTTPBody:body];                        NSData *returnData = [NSURLConnection sendSynchronousRequest:myRequest returningResponse:nil error:&err];                                                            id jsonObj = [NSJSONSerialization JSONObjectWithData:returnData options:noErr error:nil];                        return jsonObj;        }                                        @end                        @implementation FileDetail        +(FileDetail *)fileWithName:(NSString *)name data:(NSData *)data {            FileDetail *file = [[self alloc] init];            file.name = name;            file.data = data;            return file;        }        @end  

使用方法
NSData *imageData = UIImageJPEGRepresentation(image,0.8);       FileDetail *file = [FileDetail fileWithName:@"avatar.jpg" data:imageData];       NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:                               file,@"file",                               @"upload",@"action",                               nil nil];       NSDictionary *result = [HttpRequest upload:@"http://upload.corp.reco.cn/uploadimage" widthParams:params];       NSLog(@"%@",result);  
</div> </div>