在iPhone上将图片上传到服务器

5

我希望能够从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);

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


https://dev59.com/AnHYa4cB1Zd3GeqPPsdS#16397026 - Buntylm
希望这可以帮到你 :) - Augustine P A
6个回答

23

给出相同的答案2次。 如何在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];
 }

4
你用的获取图片的PHP代码是什么?$_FILES['???']['???']是什么意思? - denikov
@BuntyM如果图片是在iPhone上拍摄的,你该怎么处理?我们如何知道使用UIImagePNGRepresentation还是setData:UIImageJPEGRepresentation? - Supertecnoboff

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
谢谢伙计 :)...它有所帮助 - Nilesh Kumar
1
非常感谢,超级的好。 - shan

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

它的表现非常出色。


我正在使用这段代码,但它仍然给我与我在问题中提到的相同的错误。 - Hawk-Eye
我的返回字符串是这样的:返回字符串为:{"Message":"请求无效。","ModelState":{"response":["该键是无效的 JQuery 语法,因为它缺少一个闭合括号\r\n参数名称:key"]}},有什么想法吗? - Luke Irvin
这是来自你的服务器端的内容。。与应用程序端无关.. 请检查您的API后端以解决此错误。 - Ahmed Z.

1
请您看一下以下代码,希望对您有所帮助。
以下是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}";
 }
?>

(或者)

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

?>


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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接