在iphone中将图像发布到服务器

时间:2013-05-08 07:00:06

标签: iphone ios objective-c xcode

我想从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);

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

6 个答案:

答案 0 :(得分:23)

给出同样的答案2时间。 How to convert image into binary format in iOS?

您可以使用CoreGraphics'方法UIImagePNGRepresentation(UIImage *image),返回NSData并保存。如果您想再次将其转换为UIImage,请使用[UIimage imageWithData:(NSData *data)]方法创建它。

- (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];
 }

答案 1 :(得分:7)

我在我的应用程序中使用了此代码并且工作正常......

//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");
                           }

                       }];

答案 2 :(得分:3)

我使用了这段代码

// create request 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];                                 

[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[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];

// 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];

它就像一个魅力。

答案 3 :(得分:1)

你能看到以下代码吗?我希望它会对你有所帮助。

以下是iOS代码

//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)编码图像上传随机名称。它也会将图像链接作为响应。

<?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);  

<强>(OR)

System.Xaml.XamlXmlReaderSettings xmlsettings = new System.Xaml.XamlXmlReaderSettings();
        if(dllFile != null) { 
            Assembly wfAssembly = Assembly.Load(dllFile);
            xmlsettings.LocalAssembly = wfAssembly;
        }

        System.IO.StringReader stringReader = new System.IO.StringReader(xaml);
        XamlXmlReader reader = new XamlXmlReader(stringReader, xmlsettings);
        ActivityXamlServicesSettings settings = new ActivityXamlServicesSettings { CompileExpressions = true };
        Activity activity = System.Activities.XamlIntegration.ActivityXamlServices.Load(reader, settings);

&GT?;

答案 4 :(得分:0)

我使用了这段代码,但效果很好。

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

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];

答案 5 :(得分:0)

我已经制作了块方法,你可以使用所有类只创建NSObject,例如你创建了

 AFClass.h 
 AFClass.m 

所以在你的类头文件中写这行(这是类方法,所以你也可以简单地按类名调用)

+(NSURLSessionDataTask *)postImageRequestWithURL:(NSString *)URL andParam:(NSDictionary *)param withImages:(NSDictionary *)imageArray response:(void (^)(NSDictionary *posts, NSError *error))block;

在AFClass.m类中编写此代码

+(NSURLSessionDataTask *)postImageRequestWithURL:(NSString *)URL andParam:(NSDictionary *)param withImages:(NSDictionary *)imageArray response:(void (^)(NSDictionary *posts, NSError *error))block
{
  //show Progress hud 
  [SVProgressHUD showWithStatus:@"Loading..."];

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:URL parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
    for (NSString *strKey  in [imageArray allKeys])
    {
        if ([[imageArray valueForKey:strKey] isKindOfClass:[NSData class]])
        {

            NSString *strFilename = [NSString stringWithFormat:@"%u.jpg",arc4random()];

            [formData appendPartWithFileData:[imageArray valueForKey:strKey] name:strKey fileName:strFilename mimeType:@"image/jpeg"];
        }
    }
} error:nil];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSURLSessionUploadTask *uploadTask;

uploadTask = [manager
              uploadTaskWithStreamedRequest:request
              progress:^(NSProgress * _Nonnull uploadProgress)
              {
              }
              completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error)
              {
                  if (error)
                  {
                      [SVProgressHUD dismiss];
                      if (block)
                      {
                          block(nil, error);
                      }
                  }
                  else
                  {
                      [SVProgressHUD dismiss];
                      if (block)
                      {
                          block(responseObject, nil);
                      }
                  }
              }];
    [uploadTask resume];

    return uploadTask;
}

现在我调用这个类方法在这里我给出了示例

// Set Your URL Here 
NSString *strURL = @“Write your URL Here”

// Set Your Post Data Here
NSMutableDictionary *postData = [NSMutableDictionary dictionaryWithDictionary:@{@"user_id”:@“54”,@“first_name”:@“Jignesh”}];

// Here you can send multiple image convert your UIimage to NSData            
NSDictionary *profileData = @{@"uploaded_file":UIImageJPEGRepresentation(profilePic,1.0),@"uploaded_file1”:UIImageJPEGRepresentation(profilePic1,1.0)};

现在调用您的类上传图像的方法

 [AFClass postImageRequestWithURL:strURL andParam:postData withImages:profileData response:^(NSDictionary *response, NSError *error)
    {
       // Here is your Response  
    }];