上传图片

//imagePath 图片路径

- (void)sendServer:(NSString *)imagePath

{

NSString *urlString = kChangHeadImage;

urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *url = [NSURL URLWithString:urlString];

//    NSString *localPath = [[NSBundle mainBundle] pathForResource:imagePath ofType:nil];

NSString *localPath = imagePath;

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

request.HTTPMethod = @"POST";

NSDateFormatter *myDate = [[NSDateFormatter alloc]init];

[myDate setDateFormat:@"yyyy-MM-DD HH:mm:ss"];

NSString *date = [myDate stringFromDate:[NSDate date]];

//随机数

// 要保存在服务器上的文件名

NSString *uploadFileName = [[FenXiang readUserMassage].uid stringByAppendingString:date];

NSMutableData *dataM = [NSMutableData data];

NSString *str = [NSString stringWithFormat:@"\r\n--%@\r\n", boundary];

[dataM appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];

str = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\" \r\n", uploadFileName];

[dataM appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];

[dataM appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

[dataM appendData:[NSData dataWithContentsOfFile:localPath]];

str = [NSString stringWithFormat:@"\r\n--%@--\r\n", boundary];

[dataM appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];

request.HTTPBody = dataM;

// 6. 指定请求头 Content-Type,告诉服务器是上传文件

NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];

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

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];

// 数据处理代码...

NSLog(@"%@", result);

}];

}

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