下面是ios通过http上传图片的类,在网上找的资料后来因为需求不同就改了方法的一些参数,读者可参考自己需要读懂代码然后更改参数等。。。
1.SubmitPic.h
#import <Foundation/Foundation.h>
@interface SubmitPic : NSObject
@property(nonatomic,retain)NSMutableData *receiveData;
-(void)submitPics:(NSMutableDictionary*)array withModel:(NSString*)str;
@property(nonatomic,assign)NSUInteger sum;//用来记录数组元素的个数
@property(nonatomic,assign)NSUInteger temp;//累加器
@property(nonatomic,retain)NSMutableDictionary *dic;
@property(nonatomic,retain)NSString *model;
@property(nonatomic,retain)NSString *adjunts;
@end
2.SubmitPic.m
//
// SubmitPic.m
// MWTeck
//
// Created by 谢艳 on 14-7-3.
// Copyright (c) 2014年 com.mwteck. All rights reserved.
//
#import "SubmitPic.h"
@implementation SubmitPic
@synthesize adjunts;
-(id)init
{
if (self == [super init]) {
adjunts = [[NSString alloc]init];
}
return self;
}
-(void)submitPics:(NSMutableDictionary *)array withModel:(NSString *)str
{
_receiveData = [[NSMutableData alloc]init];
_sum = [array count]-3;
_dic = [[NSMutableDictionary alloc]init];
_dic = array;
_model = [NSString stringWithString:str];
NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
//根据url初始化request
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mwteck.eicp.net:81/upDownload/uploadFile.action"]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60];
//分界线 --AaB03x
NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
//结束符 AaB03x--
NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
//得到图片的data
NSData* data;
UIImage *image = [array objectForKey:[NSString stringWithFormat:@"pic%d",_temp]];
//判断图片是不是png格式的文件
if (UIImagePNGRepresentation(image)) {
//返回为png图像
data = UIImagePNGRepresentation(image);
}else {
//返回为JPEG图像。
data = UIImageJPEGRepresentation(image, 1.0);
}
//http body的字符串
NSMutableString *body=[[NSMutableString alloc]init];
//参数的集合的所有key的集合
NSArray *keys= [array allKeys];
//遍历keys
for(int i=0;i<[keys count];i++)
{
//得到当前key
NSString *key=[keys objectAtIndex:i];
if(![key isEqualToString:@"pic"])
{
//添加分界线,换行
[body appendFormat:@"%@\r\n",MPboundary];
//添加字段名称,换2行
[body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
//添加字段的值
[body appendFormat:@"%@\r\n",[array objectForKey:key]];
}
NSLog(@"添加字段的值==%@",[array objectForKey:key]);
}
添加分界线,换行
[body appendFormat:@"%@\r\n",MPboundary];
//声明pic字段,文件名为boris.png
[body appendFormat:@"Content-Disposition: form-data; name=\"tempFile\"; filename=\"boris.png\"\r\n"];
//声明上传文件的格式
[body appendFormat:@"Content-Type: image/png\r\n\r\n"];
//声明结束符:--AaB03x--
NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",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", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
//设置http body
[request setHTTPBody:myRequestData];
//http method
[request setHTTPMethod:@"POST"];
// NSHTTPURLResponse *urlResponese = nil;
// NSError *error = [[NSError alloc]init];
// NSData* resultData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponese error:&error];
// NSString* result= [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
// if([urlResponese statusCode] >=200&&[urlResponese statusCode]<300){
// NSLog(@"返回结果=====%@",result);
// return result;
// }
// return nil;
//建立连接,设置代理
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];
//设置接受response的data
if (conn) {
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// This method is called when the server has determined that it
// has enough information to create the NSURLResponse.
[_receiveData setLength:0];
NSInteger statusCode = [((NSHTTPURLResponse *)response) statusCode];
if (statusCode > 400)
{
[connection cancel]; // stop connecting; no more delegate messages
// [_delegate didFinshedSubmitPic:nil withMsg:@"网络错误,请重试"];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
[_receiveData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// [_delegate didFinshedSubmitPic:nil withMsg:@"网络错误,请重试"];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data
// [_refreshControl endRefreshing];
//解析数据
// [_delegate AllElevatorsRequestFinished:0 withError:@"数据获取失败"];
NSError *jsonError;
NSDictionary *dictionary = [[NSDictionary alloc]init];
NSString *str = [[NSString alloc]initWithData:_receiveData encoding:NSUTF8StringEncoding];
str = [str stringByReplacingOccurrencesOfString:@"\'" withString:@"\""];
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
if (dictionary) {
_temp++;
//结束传图片
if (_temp >= _sum) {
adjunts = [adjunts stringByAppendingString:[NSString stringWithFormat:@"%@",[dictionary objectForKey:@"id"]]];
// 返回
//[_delegate didFinshedSubmitPic:adjunts withMsg:nil];
}
//继续上传图片
else
{
adjunts = [adjunts stringByAppendingString:[NSString stringWithFormat:@"%@,",[dictionary objectForKey:@"id"]]];
[self submitPics:_dic withModel:_model];
}
}
else
{
// [_delegate didFinshedSubmitPic:nil withMsg:@"上传失败"];
}
}
@end