IOS图片上传功能实现总结

IOS图片上传主要分两种方式实现,一个是将图片信息以表单的形式上传,一种是将图片以JSON的格式上传。

首先要讲的是以这两个方式上传的一个比较明显的区别就是HTTP Header是如何标记的,以表单的形式上传时HTTP Header应该设置为multipart/form-data,以JSON格式上传时HTTP Header应该设置为application/json。


 


  1. Content-Type: multipart/form-data; boundary=${bound}


 ​


  1. Content-Type: application/json



了解了这些那我们在IOS项目中应该如何运用他们呢?


一、表单上传图片

 ​


  1. //分界线的标识符
  2. NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
  3. //根据url初始化request
  4. NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
  5. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
  6. timeoutInterval:10];
  7. //分界线 --AaB03x
  8. NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
  9. //结束符 AaB03x--
  10. NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
  11. //要上传的图片
  12. UIImage *image=[params objectForKey:@"pic"];
  13. //得到图片的data
  14. NSData* data = UIImagePNGRepresentation(image);
  15. //http body的字符串
  16. NSMutableString *body=[[NSMutableString alloc]init];
  17. //参数的集合的所有key的集合
  18. NSArray *keys= [params allKeys];

  19. //遍历keys
  20. for(int i=0;i<[keys count];i++)
  21. {
  22. //得到当前key
  23. NSString *key=[keys objectAtIndex:i];
  24. //如果key不是pic,说明value是字符类型,比如name:Boris
  25. if(![key isEqualToString:@"pic"])
  26. {
  27. //添加分界线,换行
  28. [body appendFormat:@"%@\r\n",MPboundary];
  29. //添加字段名称,换2行
  30. [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
  31. //添加字段的值
  32. [body appendFormat:@"%@\r\n",[params objectForKey:key]];
  33. }
  34. }

  35. ////添加分界线,换行
  36. [body appendFormat:@"%@\r\n",MPboundary];
  37. //声明pic字段,文件名为boris.png
  38. [body appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"boris.png\"\r\n"];
  39. //声明上传文件的格式
  40. [body appendFormat:@"Content-Type: image/png\r\n\r\n"];

  41. //声明结束符:--AaB03x--
  42. NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
  43. //声明myRequestData,用来放入http body
  44. NSMutableData *myRequestData=[NSMutableData data];
  45. //将body字符串转化为UTF8格式的二进制
  46. [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
  47. //将image的data加入
  48. [myRequestData appendData:data];
  49. //加入结束符--AaB03x--
  50. [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];

  51. //设置HTTPHeader中Content-Type的值
  52. NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
  53. //设置HTTPHeader
  54. [request setValue:content forHTTPHeaderField:@"Content-Type"];
  55. //设置Content-Length
  56. [request setValue:[NSString stringWithFormat:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
  57. //设置http body
  58. [request setHTTPBody:myRequestData];
  59. //http method
  60. [request setHTTPMethod:@"POST"];

  61. //建立连接,设置代理
  62. NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

  63. //设置接受response的data
  64. if (conn) {
  65. mResponseData = [[NSMutableData data] retain];
  66. }




二、JSON上传图片

    1. //根据url初始化request
    2. NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
    3. cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
    4. timeoutInterval:10];

    5. //要上传的图片
    6. UIImage *image=[params objectForKey:@"pic"];
    7. //得到图片的data
    8. NSData* data = UIImagePNGRepresentation(image);
    9. //base64编码
    10. NSString *photoStr = [data base64Encoding];

    11. //参数字典
    12. NSDictionary *params = [[NSDictionary alloc] init];
    13. [params setObject:@{@"avatar": photoStr} forKey:@"profile"];
    14. NSData *myRequestData = [NSMutableData dataWithData:[NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil]];

    15. //设置http header
    16. [request.request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
    17. [request.request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    18. //设置http body
    19. [request setHTTPBody:myRequestData];
    20. //http method
    21. [request setHTTPMethod:@"POST"];

    22. //建立连接,设置代理
    23. NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    24. //设置接受response的data
    25. if (conn) {
    26. mResponseData = [[NSMutableData data] retain];
    27. }