在iphone中发布图像到服务器

我想从iphone发布/共享图像到服务器。 图像准备分享。 我正在使用大多数网站使用下面的代码显示的方式

NSData *imageData = UIImageJPEGRepresentation(image, 100); NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; NSString *boundary = @"0x0hHai1CanHazB0undar135"; NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; [request setValue:contentType forHTTPHeaderField:@"Content-Type"]; NSMutableData *body = [NSMutableData data]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding: NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"imageToAttach\"; filename=\"%@\"\r\n",fileName]dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:imageData]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:body]; NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; NSLog(@"%@",returnString); 

但它给了我一些内部服务器错误,然后我指出,服务器要求图像的stream字节..我可以将图像转换成stream,然后将该stream发布到服务器?

给出相同的答案2时间。 如何在iOS中将图像转换为二进制格式?

你可以使用CoreGraphics的方法UIImagePNGRepresentation(UIImage *image) ,它返回NSData并保存它。 如果你想再次转换成UIImage使用[UIimage imageWithData:(NSData *data)]方法创build它。

 - (void)sendImageToServer { UIImage *yourImage= [UIImage imageNamed:@"image.png"]; NSData *imageData = UIImagePNGRepresentation(yourImage); NSString *postLength = [NSString stringWithFormat:@"%d", [imageData length]]; // Init the URLRequest NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setHTTPMethod:@"POST"]; [request setURL:[NSURL URLWithString:[NSString stringWithString:@"http://yoururl.domain"]]]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setHTTPBody:imageData]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if (connection) { // response data of the request } [request release]; } 

我在我的应用程序中使用此代码,它工作正常…

 //create request NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; //Set Params [request setHTTPShouldHandleCookies:NO]; [request setTimeoutInterval:60]; [request setHTTPMethod:@"POST"]; //Create boundary, it can be anything NSString *boundary = @"------VohpleBoundary4QuqLuM1cE5lMwCy"; // set Content-Type in HTTP header NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; [request setValue:contentType forHTTPHeaderField: @"Content-Type"]; // post body NSMutableData *body = [NSMutableData data]; //Populate a dictionary with all the regular values you would like to send. NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init]; [parameters setValue:param1 forKey:@"param1-name"]; [parameters setValue:param2 forKey:@"param2-name"]; [parameters setValue:param3 forKey:@"param3-name"]; // add params (all params are strings) for (NSString *param in parameters) { [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"%@\r\n", [parameters objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]]; } NSString *FileParamConstant = @"imageParamName"; NSData *imageData = UIImageJPEGRepresentation(imageObject, 1); //Assuming data is not nil we add this to the multipart form if (imageData) { [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Type:image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:imageData]; [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; } //Close off the request with the boundary [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; // setting the body of the post to the request [request setHTTPBody:body]; // set URL [request setURL:[NSURL URLWithString:baseUrl]]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; if ([httpResponse statusCode] == 200) { NSLog(@"success"); } }]; 

我用这个代码

 // create request NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; [request setHTTPShouldHandleCookies:NO]; [request setTimeoutInterval:30]; [request setHTTPMethod:@"POST"]; // set Content-Type in HTTP header NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; [request setValue:contentType forHTTPHeaderField: @"Content-Type"]; // post body NSMutableData *body = [NSMutableData data]; // add params (all params are strings) for (NSString *param in _params) { [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]]; } // add image data NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0); if (imageData) { [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:imageData]; [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; } [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; // setting the body of the post to the reqeust [request setHTTPBody:body]; // set the content-length NSString *postLength = [NSString stringWithFormat:@"%d", [body length]]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; // set URL [request setURL:requestURL]; 

它就像一个魅力。

你能看到下面的代码,我希望它会对你有帮助。

这里是iOS代码

 -(void)createConnectionRequestToURL:(NSString *)urlStr withImage:(UIImage*)image withImageName:(NSString*)imageName { NSData *imageData = UIImageJPEGRepresentation(image, 90); NSString *urlString = urlStr; // setting up the request object now NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:urlString]]; [request setHTTPMethod:@"POST"]; NSString *boundary = [[NSString alloc]init]; 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:[@"Content-Disposition: form-data; name=\"file\"; filename=\"test.png\"rn" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Type: application/%@.jpg\r\n\r\n",imageName] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[NSData dataWithData:imageData]]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:body]; //Using Synchronous Request. You can also use asynchronous connection and get update in delegates NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; NSLog(@"--------%@",returnString); } 

在这里findserverside(PHP)编码图像随机名称上传。 也会给图像链接作为回应。

 //Create a folder named images in your server where you want to upload the image. // And Create a PHP file and use below code . <?php $uploaddir = 'images/'; $ran = rand () ; $file = basename($_FILES['userfile']['name']); $uploadfile = $uploaddir .$ran.$file; if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { echo "www.host.com/.../images/{$uploadfile}"; } ?> 

(要么)

 <?php $request_body = @file_get_contents('php://input'); foreach (getallheaders() as $name => $value) { if ($FileName=="FileName") { $header=$value; break; } } $uploadedDir = "directory/"; @mkdir($uploadedDir); file_put_contents($uploadedDir."/".$FileName.".txt", $request_body.PHP_EOL, FILE_APPEND); header('X-PHP-Response-Code: 202', true, 202); 

?>

我用这个代码,它工作正常。

如果你想要更多的准确性和速度,你可以压缩图像然后上传,但压缩是一个可选的部分。

 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; [request setHTTPShouldHandleCookies:NO]; [request setTimeoutInterval:30]; [request setHTTPMethod:@"POST"]; // RP: Empaquetando datos NSMutableDictionary* _params = [[NSMutableDictionary alloc] init]; [_params setObject:[NSString stringWithFormat:@"%@",loginoneid] forKey:@"user_id"]; [_params setObject:[NSString stringWithFormat:@"%@",_strpostid] forKey:@"post_id"]; // the boundary string : a random string, that will not repeat in post data, to separate post data fields. NSString *BoundaryConstant = @"V2ymHFg03ehbqgZCaKO6jy"; // string constant for the post parameter 'file' NSString *FileParamConstant = @"files[]"; //RP: Configurando la dirección NSURL *requestURL = [[NSURL alloc] initWithString:@"http://www.hugosys.in/www.nett-torg.no/api/rpcs/uploadfiles/"]; // set Content-Type in HTTP header NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant]; [request setValue:contentType forHTTPHeaderField: @"Content-Type"]; // post body NSMutableData *body = [NSMutableData data]; // add params (all params are strings) for (NSString *param in _params) { [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]]; } if (imageData) { printf("appending image data\n"); [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\'%@\'; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:imageData]; [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; } [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]]; // setting the body of the post to the reqeust [request setHTTPBody:body]; // set the content-length // set the content-length NSString *postLength = [NSString stringWithFormat:@"%d", [body length]]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; // set URL [request setURL:requestURL]; NSURLResponse *response = nil; NSError *err = nil; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err]; dispatch_async(dispatch_get_main_queue(), ^{ NSString *str = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];