使用NSURLSession简单做一个上传图片的方法

        通常上传文件、图片。使用http请求的POST方法,在body体中还有一些固定的格式。iOS SDK中的NSURLSession是一个heigh-level API,由于上传图片是一次性请求,实现起来还是很方便的:下面是关键代码,一个函数即可可以实现:

#define UploadImageBoundary @"KhTmLbOuNdArY0001"
- (NSURLRequest *)POSTImage:(NSString *)URLString data:(NSData *)imageData name:(NSString*)name finish:(RequestFinish)finish{
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString]];
    [request setHTTPMethod:@"POST"];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [request setTimeoutInterval:20];
    NSString* headerString = [NSString stringWithFormat:@"multipart/form-data; charset=utf-8; boundary=%@",UploadImageBoundary];
    [request setValue:headerString forHTTPHeaderField:@"Content-Type"];
    
    NSMutableData* requestMutableData = [NSMutableData data];
    NSMutableString* myString = [NSMutableString stringWithFormat:@"--%@\r\n",UploadImageBoundary];
    [myString appendString:@"Content-Disposition: form-data; name=\"appid\"\r\n\r\n"];/*这里要打两个回车*/
    [myString appendString:@"100118"];
    [myString appendString:[NSString stringWithFormat:@"\r\n--%@\r\n",UploadImageBoundary]];
    [myString appendString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n",name]];
    [myString appendString:@"Content-Type: image/jpeg\r\n\r\n"];
    /*转化为二进制数据*/
    [requestMutableData appendData:[myString dataUsingEncoding:NSUTF8StringEncoding]];
    /*文件数据部分,也是二进制*/
    [requestMutableData appendData:imageData];
    /*已--boundary结尾表明结束*/
    [requestMutableData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",UploadImageBoundary] dataUsingEncoding:NSUTF8StringEncoding] ];
    
    request.HTTPBody = requestMutableData;
    
    
    /*开始上传*/
    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    sessionConfig.timeoutIntervalForRequest = 20;
    NSURLSession* session  = [NSURLSession sessionWithConfiguration:sessionConfig
                                                        delegate:self
                                                   delegateQueue:nil];
    
    NSURLSessionDataTask * uploadtask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        if (finish) {
            finish(nil,dictionary,error);
        }
    }];
    [uploadtask resume];
    return request;
}
调用方法如下:

-(void) uploadCover:(UIImage*)image{
    NSData * imagedata = UIImageJPEGRepresentation(image,1.0);
    
    [[Networking sharedInstance] POSTImage:@"http:/xxxxx/ndfs/uploadPhoto.do" data:imagedata name:self.videoName finish:^( id responseObject, NSError *error) {
        
        DDLogWarn(@"uploadCover: %@",responseObject);
    }];
}


使用NSURLSession简单做一个上传图片的方法_第1张图片


上面是抓包结果。第9行开始就是图片的data内容了。其中--KhTmLbOuNdArY0001是分割数据用的,需要以“--”开头,后面随意
曾经应为少了一个回车(代码中有注释)导致server应答400,说Retrofit - Multipart request: Required MultipartFile parameter 'file' is not present。
如果是上传大文件,怎要分块上传。每一块都是这个原理。

你可能感兴趣的:(NSURLSession,上传图片)