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

在iphone中将图像发布到服务器,iphone,ios,objective-c,xcode,Iphone,Ios,Objective C,Xcode,我想从iphone向服务器发布/共享图像。图像已准备好共享。我使用的方式,大多数网站显示使用下面的代码 NSData *imageData = UIImageJPEGRepresentation(image, 100); NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; NSString *boundary = @"0x0hHai1C

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

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

给出了相同的回答2次。

您可以使用
CoreGraphics
”方法
UIImagePNGRepresentation(UIImage*image)
,该方法返回并保存数据。如果您想再次将其转换为
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];
 }
我用了这个密码

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

它就像一个符咒

我在我的应用程序中使用了这段代码,效果很好

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

                       }];

我使用了这个代码,它工作得很好

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

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

你能看到下面的代码吗?我希望它能对你有所帮助

这是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);
}
在这里查找服务器端(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}";
 }
?>
//在服务器中创建一个名为images的文件夹,以便上载图像。
//创建一个PHP文件并使用下面的代码。
(或)


我已经创建了块方法,您可以使用所有类来创建NSObject,例如您已经创建了

 AFClass.h 
 AFClass.m 
所以,在类头文件中写这一行(这是类方法,所以您也可以简单地通过类名调用)

并在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;
}
现在调用类方法上传图像

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

[参考sunil的答案][1][1]:希望这能对您有所帮助:)我正在使用此代码,但它给我的错误与我在问题中提到的相同。我的返回字符串是:返回字符串是:{“Message”:“请求无效”。,“ModelState”:{“response”:[“该键是无效的JQuery语法,因为它缺少一个右括号\r\n参数名称:key”]},有什么想法吗?这是来自服务器端的内容..与应用程序端无关..检查api后端是否存在此错误用于获取图像的PHP代码是什么?是什么$u文件['???']['??']?@BuntyM如果图像是在iPhone上拍摄的,你会怎么做。我们如何知道如何使用UIImagePngResentation或setData:UIImageJPEGresentation??谢谢,伙计:)…这很有帮助真的谢谢..超级
+(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  
    }];