iphone开发:上传图片
上传后,需要服务器那边进行解码保存为图片。以后只需要用url来获得这个图片。
- (void)right_nav_baritem_return
{
//向服务器提交表单或者是数据
int size = 204800;
int current_size = 0;
int actual_size = 0;
NSData *data = UIImageJPEGRepresentation(image_photo,1.0);
current_size = [data length];
if (current_size > size)
{
actual_size = size/current_size;
data = UIImageJPEGRepresentation(image_photo,actual_size);
}
activity_indicator = [[UIActivityIndicatorViewalloc] initWithFrame:CGRectMake(150, 130, 20, 20)];
[activity_indicatorsetActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
[self.viewaddSubview:activity_indicator];
[activity_indicatorstartAnimating];
[selfperformSelectorInBackground:@selector(upload_user_picker_image:) withObject:data];
}
- (void)upload_user_picker_image:(NSData*)data
{
NSString *lat_long = [NSStringstringWithFormat:@"{\"latitude\":\"%f\",\"longitude\":\"%f\"}",lattitude,longitude];
NSString *urlString = @"http://pluginwebtest.shopal.jp/api/v1/upload1/add_upload_shop.php";
NSMutableURLRequest *request= [[[NSMutableURLRequestalloc] init] autorelease];
[request setURL:[NSURLURLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"0xKhTmLbOuNdArY";
NSString *contentType = [NSStringstringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *postbody = [NSMutableDatadata];
NSMutableString *str=[[NSMutableStringalloc] init];
//第一个字段
[str appendFormat:@"\r\n\r\n--%@\r\n" ,boundary];
[str appendFormat: @"Content-Disposition:form-data; name=\"product_desc\"\r\n\r\n"];
if (product_desc)
{
[str appendFormat:product_desc];
}
else
{
[str appendFormat:@"null"];
}
//第二个字段
[str appendFormat:@"\r\n\r\n--%@\r\n" ,boundary];
[str appendFormat: @"Content-Disposition:form-data; name=\"product_category\"\r\n\r\n"];
if (product_category)
{
[str appendFormat:product_category];
}
else
{
[str appendFormat:@"null"];
}
//第三个字段
[str appendFormat:@"\r\n\r\n--%@\r\n" ,boundary];
[str appendFormat: @"Content-Disposition:form-data; name=\"lat_long\"\r\n\r\n"];
[str appendFormat:lat_long];
//第四个字段
NSString *image_data = [data base64Encoded];
[str appendFormat:@"\r\n\r\n--%@\r\n" ,boundary];
[str appendFormat: @"Content-Disposition:form-data; name=\"image\"\r\n\r\n"];
[str appendFormat:image_data];
//编码
[postbody appendData:[str dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
[str release];
NSData *returnData = [NSURLConnectionsendSynchronousRequest:request returningResponse:nilerror:nil];
NSString *returnString = [[NSStringalloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"returnString is %@",returnString);
[returnString release];
[activity_indicatorstopAnimating];
UIAlertView *alert = [[UIAlertViewalloc] initWithTitle:@"レポート" message:@"アップロードが成功易做图\n上传成功。" delegate:self cancelButtonTitle:@"決定"otherButtonTitles:nil, nil];
[alert setDelegate:self];
[alert show];
[alert release];
}
摘自 云怀空-abel
补充:移动开发 , IOS ,