标签:
由于iOS无法通过html表单来上传图片,因此想要上传图片,必须实现http请求,而不能像其他语言那样通过html表单的post就能上传。以上的这些格式,是http的规范,每个空行,空格都是必须的。
#define HTTP_CONTENT_BOUNDARY @"WANPUSH" -(BOOL)httpPutData:(NSString*)strUrl FilePath:(NSString*)filePath DataType:(NSString*)dataType { strUrl = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL* url = [NSURL URLWithString:strUrl]; NSData* data = [NSData dataWithContentsOfFile:filePath]; NSString* fileName = [filePath lastPathComponent]; NSString* strBodyBegin = [NSString stringWithFormat:@"--%@\nContent-Disposition: form-data; name=\"%@\"; filename=\"%@\"\nContent-Type: %@\n\n", HTTP_CONTENT_BOUNDARY, @"file", fileName, dataType]; NSString* strBodyEnd = [NSString stringWithFormat:@"\n--%@--",HTTP_CONTENT_BOUNDARY]; NSMutableData *httpBody = [NSMutableData data]; [httpBody appendData:[strBodyBegin dataUsingEncoding:NSUTF8StringEncoding]]; [httpBody appendData:data]; [httpBody appendData:[strBodyEnd dataUsingEncoding:NSUTF8StringEncoding]]; NSMutableURLRequest* httpPutRequest = [[NSMutableURLRequest alloc] init]; [httpPutRequest setURL:url]; [httpPutRequest setHTTPMethod:@"POST"]; [httpPutRequest setTimeoutInterval: 60000]; [httpPutRequest setValue:[NSString stringWithFormat:@"%@", @(httpBody.length)] forHTTPHeaderField:@"Content-Length"]; [httpPutRequest setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",HTTP_CONTENT_BOUNDARY] forHTTPHeaderField:@"Content-Type"]; httpPutRequest.HTTPBody = httpBody; NSHTTPURLResponse* httpResponse = nil; NSError *error = [[NSError alloc] init]; NSData *responseData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&httpResponse error:&error]; if (httpResponse == nil) { NSLog(@"url: %@\nerror_code: %@", strUrl, error); return NO; } if (httpResponse.statusCode != 200) { NSLog(@"url: %@\nHTTP response: %ld", strUrl, (long)httpResponse.statusCode); return NO; } return YES; }
标签:
原文地址:http://blog.csdn.net/topwangpeng/article/details/43409429