上传图片的实现
Posted 华少不思议
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了上传图片的实现相关的知识,希望对你有一定的参考价值。
- (IBAction)uploadButton:(id)sender {
UIImage *image = [UIImage imageNamed:@"1.jpg"];
NSData *imageData = UIImageJPEGRepresentation(image,
0.5);
NSString *urlString [email protected]"http://192.168.1.113:8090/
NSMutableURLRequest *request = [[NSMutableURLRequest
alloc] init] ;
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = [NSString
stringWithString:@"---------------------------14737809831
466499882746641449"];
NSString *contentType = [NSString
stringWithFormat:@"multipart/form-data;boundary=
%@",boundary];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--
%@\r\n",boundary]
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString
stringWithString:@"Content-Disposition:form-data; name=
\"userfile\"; filename=\"2.png\"\r\n"]
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString
stringWithString:@"Content-Type: application/octet-stream
\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--
%@--\r\n",boundary]
dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection
sendSynchronousRequest:request returningResponse:nilerror:nil];
NSString *returnString = [[NSString alloc]
initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"3-%@",returnString);
UIImage *myImage = [UIImage imageWithData:returnData];
[imageView setImage:myImage];
[self.view addSubview:imageView];
以上是关于上传图片的实现的主要内容,如果未能解决你的问题,请参考以下文章