当前位置:首页 > 操作系统 > Ios

iOS post上传图片

在项目开发中,经常会碰到图片上传,有些后台比较坑,上传图片一定需要按照服务端那边格式把body post过去才行,格式一定要正确,你懂的,有些在客户端直接传流即可。下面说的比较坑的图片怎么post,源代码网上也比较多,直接分享下代码。技术分享技术分享

上面有注释的很清晰就不一一解释了。

1._mResponseData 是NSMutableData对象。

2.解释下ImageName,这是个key,就是你要上传给服务器的入参,看服务器怎么给你定义的,我这边是ImageName。

3.parameters这个字典封装后台给你定义的入参,一般都以json格式,我这边parameters里面的入参有ImageName

4.请求也粘贴在下面,可直接复制代码,返回的数组需要自己改动下。

#pragma mark - 上传图片

- ( void )requestPhotoApi:( NSDictionary *)parameters;

{

    NSString *urlAsString = [ NSString stringWithFormat : @"%@?key=%@&" ,[ kTestRequestURL stringByAppendingString : @"sys/webapi/common/upload.do" ],[ FAUserModel getUserToken ]];

    // 分界线的标识符

    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x" ;

    // 根据 url 初始化 request

    

    NSMutableURLRequest * request = [ NSMutableURLRequest requestWithURL :[ NSURL URLWithString :urlAsString]

                                                            cachePolicy : NSURLRequestUseProtocolCachePolicy

                                                        timeoutInterval : 20 ];

    // 分界线 --AaB03x

    NSString *MPboundary=[[ NSString alloc ] initWithFormat : @"--%@" ,TWITTERFON_FORM_BOUNDARY];

    // 结束符 AaB03x--

    NSString *endMPboundary=[[ NSString alloc ] initWithFormat : @"%@--" ,MPboundary];

    //// 要上传的图片

    UIImage *image=[parameters objectForKey : @"imageName" ];

    // 得到图片的 data

    NSData *data = UIImagePNGRepresentation (image);

    //http body 的字符串

    NSMutableString *body=[[ NSMutableString alloc ] init ];

    // 参数的集合的所有 key 的集合

    NSArray *keys= [parameters allKeys ];

    // 遍历 keys

    for ( int i= 0 ;i<[keys count ];i++){

        // 得到当前 key

        NSString *key=[keys objectAtIndex :i];

        // 如果 key 不是 pic ,说明 value 是字符类型,比如 name Boris

        if (![key isEqualToString : @"imageName" ]) {

            // 添加分界线,换行

            [body appendFormat : @"%@rn" ,MPboundary];

            // 添加字段名称,换 2

            [body appendFormat : @"Content-Disposition: form-data; name="%@"rnrn" ,key];

            // 添加字段的值

            [body appendFormat : @"%@rn" ,[parameters objectForKey :key]];

        }

    }

    //// 添加分界线,换行

    [body appendFormat : @"%@rn" ,MPboundary];

    // 声明 pic 字段,文件名为 boris.png

    [body appendFormat : @"Content-Disposition: form-data; name="pic"; filename="boris.png"rn" ];

    // 声明上传文件的格式

    [body appendFormat : @"Content-Type: image/pngrnrn" ];

    // 声明结束符: --AaB03x--

    NSString *end=[[ NSString alloc ] initWithFormat : @"rn%@" ,endMPboundary];

    // 声明 myRequestData ,用来放入 http body

    NSMutableData *myRequestData=[ NSMutableData data ];

    // body 字符串转化为 UTF8 格式的二进制

    [myRequestData appendData :[body dataUsingEncoding : NSUTF8StringEncoding ]];

    // image data 加入

    [myRequestData appendData :data];

    // 加入结束符 --AaB03x--

    [myRequestData appendData :[end dataUsingEncoding : NSUTF8StringEncoding ]];

    // 设置 HTTPHeader Content-Type 的值

    NSString *content=[[ NSString alloc ] initWithFormat : @"multipart/form-data; boundary=%@" ,TWITTERFON_FORM_BOUNDARY];

    // 设置 HTTPHeader

    [request setValue :content forHTTPHeaderField : @"Content-Type" ];

    // 设置 Content-Length

    [request setValue :[ NSString stringWithFormat : @"%d" , ( int )[myRequestData length ]] forHTTPHeaderField : @"Content-Length" ];

    // 设置 http body

    [request setHTTPBody :myRequestData];

    //http method

    [request setHTTPMethod : @"POST" ];

    // 建立连接,设置代理

    NSURLConnection *conn = [[ NSURLConnection alloc ] initWithRequest :request delegate : self ];

    // 设置接受 response data

    if (conn) {

        _mResponseData = [[ NSMutableData alloc ] init ];

    }

}


#pragma mark - NSURLConnectionDelegate

- ( void )connection:( NSURLConnection *)connection didReceiveResponse:( NSURLResponse *)response

{

    [ _mResponseData setLength : 0 ];

}

- ( void )connection:( NSURLConnection *)connection didReceiveData:( NSData *)data

{

    [ _mResponseData appendData :data];

}

- ( void )connectionDidFinishLoading:( NSURLConnection *)connection

{

    

    NSDictionary *dic =  [ NSJSONSerialization JSONObjectWithData : _mResponseData options : kNilOptions error : nil ];

    NSLog ( @"%@" , dic);

    

    if ( self . buttonTag == ButtonTag ) {

        

        DLog ( @"11111:%@" ,dic[ @"data" ])

        self . uploadSevenArray = [ NSMutableArray arrayWithArray :dic[ @"data" ]];

    }

    else {

    

          DLog ( @"22222:%@" ,dic[ @"data" ])

        self . uploadEgihtArray = [ NSMutableArray arrayWithArray :dic[ @"data" ]];

    }

    

    [ self refreshSendImImage ];

    

}

- ( void )connection:( NSURLConnection *)connection didFailWithError:( NSError *)error

{

    NSLog ( @"Error: %@" , error);

}





原文:http://blog.csdn.net/defuliu66/article/details/51330239


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!