从iOS设备上传图片到PHP服务器

20

我知道这个问题之前也被问过,但我的问题有点不同。

我想从iOS设备上传一张图片到PHP服务器,并且想要在图片上传的同时发送更多的参数。我在Google上搜索了两种解决方案:

  1. 我们可以将图片作为JSON中的Base64编码的字符串进行发送。参考链接

  2. 或者我们可以使用表单数据将图片上传到服务器。我参考了这个链接。如果有人介绍给我这种方式,请帮助我在此API中添加更多的参数。

现在我的问题是,哪种方法是上传图片到服务器的最佳方式,并且我必须在同一个Web服务调用中发送更多的参数(用户名、密码和更多详细信息)。

提前致谢。


Base64总是最好的选择...尽量避免使用大标题,保持简洁。 - TtheT
1
使用第二种方法(使用边界的多部分编码)可以减少内存使用,因为您可以直接流式传输数据。此外,您的PHP后端将能够正确消耗它而无需显式解码。使用JSON需要预编码,使用Base64需要前瞻性。您不希望传递占用内存的字符串;请改为传递流。标题开销比编码为Base64要小得多。 - soulseekah
1
@soulseekah 感谢您的回复,但问题是,我想在发送图像时传递更多参数。我该如何使用第二种方法传递附加参数? - Vinay Jain
@Parcs:http://www.w3.org/Protocols/rfc1341/7_2_Multipart.html - soulseekah
你之前有使用过ASIHTTP吗? - Aklesh Rathaur
显示剩余6条评论
6个回答

38

您可以通过以下两种方式将iOS应用程序中的图像上传到PHP服务器

使用新AFNetworking

#import "AFHTTPRequestOperation.h"
#import "AFHTTPRequestOperationManager.h"

    NSString *stringUrl =@"http://www.myserverurl.com/file/uloaddetails.php?"
    NSString *string =@"http://myimageurkstrn.com/img/myimage.png"       
    NSURL *filePath = [NSURL fileURLWithPath:string];

   NSDictionary *parameters  = [NSDictionary dictionaryWithObjectsAndKeys:userid,@"id",String_FullName,@"fname",String_Email,@"emailid",String_City,@"city",String_Country,@"country",String_City,@"state",String_TextView,@"bio", nil];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    [manager POST:stringUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
     {
         [formData appendPartWithFileURL:filePath name:@"userfile" error:nil];//here userfile is a paramiter for your image 
     }
     success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSLog(@"%@",[responseObject valueForKey:@"Root"]);
         Alert_Success_fail = [[UIAlertView alloc] initWithTitle:@"myappname" message:string delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
         [Alert_Success_fail show];     

     }
     failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         Alert_Success_fail = [[UIAlertView alloc] initWithTitle:@"myappname" message:[error localizedDescription] delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
         [Alert_Success_fail show];

     }];

其次使用NSURLConnection:

-(void)uploadImage
    {       
        NSData *imageData = UIImagePNGRepresentation(yourImage);

        NSString *urlString = [ NSString stringWithFormat:@"http://yourUploadImageURl.php?intid=%@",1];

        NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
        [request setURL:[NSURL URLWithString:urlString]];
        [request setHTTPMethod:@"POST"];

        NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
        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:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", 1]] 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];

        [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    }

这两种方法都可以很好地实现从应用程序上传图像到php服务器的功能,希望这能对你有所帮助。


@Pedroinpeace 是的,那个设置在后端的 PHP 侧。 - Nitin Gohel
我尝试了这种方法,但它不起作用。我的图像路径格式为:http://dev-demo.info.bh-in-15.webhostbox.net/dv/abc/ulpoad/post/imageName,请问如何使用您的第二种方法上传图像? - Abhi
在我的情况下找不到AFHTTPRequestOperation。请帮忙解决一下。 - Sneha

0

试试这个,对我有效。

    NSData *postData = [Imagedata dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:apiString]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    NSURLResponse *response;
    NSError *err;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
    NSString *responseString = [[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding];


    NSError *jsonError;
    NSData *objectData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseDictft = [NSJSONSerialization JSONObjectWithData:objectData
                                                                   options:NSJSONReadingMutableContainers
                                                                     error:&jsonError];

0

使用AFNetworking,我是这样做的:

NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:@"myUserName" forKey:@"username"];
    [params setObject:@"1234" forKey:@"password"];
    [[AFHTTPRequestOperationLogger sharedLogger] startLogging];
    NSData *imageData;
    NSString *urlStr = [NSString stringWithFormat:@"http://www.url.com"];
    NSURL *url = [NSURL URLWithString:urlStr];

    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
       imageData = UIImageJPEGRepresentation(mediaFile, 0.5);


    NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:nil parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData)
    {
              [formData appendPartWithFileData:imageData name:@"mediaFile" fileName:@"picture.png" mimeType:@"image/png"];
    }];

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request

    success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
    {

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"File was uploaded" message:@""
                                                       delegate:self cancelButtonTitle:@"Close" otherButtonTitles: nil];
        [alert show];
    }
    failure:^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON)
    {
        NSLog(@"request: %@",request);
        NSLog(@"Failed: %@",[error localizedDescription]);
    }];


    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite)
    {
        NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
    }];
    [httpClient enqueueHTTPRequestOperation:operation];

找不到AFHTTPClient。 - Gank
@Segev,你能告诉我如何在PHP服务器上抓取这个图片吗?我很困惑图片是如何上传到服务器的,以及用什么名称来获取它? - Qasim Ali

0
-(void)uploadImage
{

NSString *mimetype = @"image/jpeg";
NSString *myimgname = _txt_fname.text; //@"img"; //upload image with this name in server PHP FILE MANAGER
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *imageDataa = UIImagePNGRepresentation(chooseImg.image);
NSDictionary *parameters =@{@"fileimg":defaults }; //@{@"uid": [uidstr valueForKey:@"id"]};

AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
//here post url and imagedataa is data conversion of image  and fileimg is the upload image with that name in the php code
NSMutableURLRequest *request =
[serializer multipartFormRequestWithMethod:@"POST" URLString:@"http://posturl/newimageupload.php"
                                parameters:parameters
                 constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                     [formData appendPartWithFileData:imageDataa
                                                 name:@"fileimg"
                                             fileName:myimgname
                                             mimeType:mimetype];
                 }];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//manager.responseSerializer = [AFHTTPResponseSerializer serializer];
AFHTTPRequestOperation *operation =
[manager HTTPRequestOperationWithRequest:request
                                 success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                     NSLog(@"Success %@", responseObject);
                                     [uploadImgBtn setTitle:@"Uploaded" forState:UIControlStateNormal];
                                     [chooseImg setImage:[UIImage imageNamed:@"invoice-icon.png"]];

                                     if([[responseObject objectForKey:@"status"] rangeOfString:@"Success"].location != NSNotFound)
                                     {
                                         [self alertMsg:@"Alert" :@"Upload sucess"];
                                     }

                                 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                     NSLog(@"Failure %@", error.description);
                                     [chooseImg setImage:[UIImage imageNamed:@"invoice-icon.png"]];
                                     uploadImgBtn.enabled = YES;

                                 }];

// 4. Set the progress block of the operation.
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {

    float myprog = (float)totalBytesWritten/totalBytesExpectedToWrite*100;
    NSLog(@"Wrote %f ", myprog);
}];

// 5. Begin!
[operation start];

}

0

试试这个。

-(void)EchoesPagePhotosUpload
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

    [self startIndicator];
});
//NSLog(@"%@",uploadPhotosArray);
NSMutableArray *uploadPhotosByteArray=[[NSMutableArray alloc] init];
conversionImage= [UIImage imageWithContentsOfFile:[uploadPhotosArray objectAtIndex:0]];

NSLog(@"conversionImage.size.height %f",conversionImage.size.height);
NSLog(@"conversionImage.size.width %f",conversionImage.size.width);
if(conversionImage.size.height>=250&&conversionImage.size.width>=250)
{
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        [self performSelectorInBackground: @selector(LoadForLoop) withObject: nil];        NSLog(@"conversionImage.size.height %f",conversionImage.size.height);
        NSLog(@"conversionImage.size.width %f",conversionImage.size.width);

        for(int img_pos=0;img_pos<[uploadPhotosArray count];img_pos++)
        {
            conversionImage= [UIImage imageWithContentsOfFile:[uploadPhotosArray objectAtIndex:img_pos]];
            NSData *imageData = UIImageJPEGRepresentation(conversionImage,1.0);
            [Base64 initialize];
            NSString *uploadPhotoEncodedString = [Base64 encode:imageData];
            //NSLog(@"Byte Array %d : %@",img_pos,uploadPhotoEncodedString);
            [uploadPhotosByteArray addObject:uploadPhotoEncodedString];

        }
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *photo_description=[webview stringByEvaluatingJavaScriptFromString:                        @"document.getElementById('UploadPicsDesc').value"];
            NSString *uploadPhotoImageName=@"uploadPhoto.jpg";
            NSDictionary *UploadpicsJsonResponseDic=[WebserviceViewcontroller EchoesUploadPhotos:profileUserId imageName:uploadPhotoImageName Image:uploadPhotosByteArray PhotoDescription:photo_description];
            //NSLog(@"%@",UploadpicsJsonResponseDic);
            NSString *UploadPhotosStatusString=[UploadpicsJsonResponseDic valueForKey:@"Status"];

            NSLog(@"UploadPhotosStatusString :%@",UploadPhotosStatusString);
            NSString *uploadPhotosCallbackstring=[NSString stringWithFormat:@"RefreshForm()"];
            [webview stringByEvaluatingJavaScriptFromString:uploadPhotosCallbackstring];
        });
    });
}
else {
    UIAlertView *ErrorAlert=[[UIAlertView alloc] initWithTitle:@"Error" message:@"Please Upload Photo Above 250x250 size" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [ErrorAlert show];
    NSLog(@"conversionImage.size.height %f",conversionImage.size.height);
    NSLog(@"conversionImage.size.width %f",conversionImage.size.width);
}
}

0

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