如何在iOS上将图像作为JSON上载到服务器上作为JSON在iOS上

问题描述:

如何将图像从iPhone上的图库作为JSON上传到服务器?我试过如下:如何在iOS上将图像作为JSON上载到服务器上作为JSON在iOS上

[Loading startLoading:YES]; 
NSString *urlString = [NSString stringWithFormat:@"http://railsboxtech.com/singing/jsn_song/register_response.php?accesstoken=%@",Access_Token]; 
//username, password, name, email, country 
NSString *parameter = [NSString stringWithFormat:@"username=%@&password=%@&fname=%@&email=%@&lname=%@&btnImage4=%@",userField.text,passField.text,fnameField.text,emailField.text,lnameField.text,btnImage4]; 
NSConnection *conn = [[NSConnection alloc] initWithDelegate:self]; 
[conn sendRequest:urlString withParaMeter:parameter withMethod:@"POST" withTag:1]; 
[conn startAsynchronousRequest]; 

如果要上传图片作为一个字符串,你必须将图像数据转换为Base64,那么你可以使用你上面的方法

: -

对于转换成一个base64字符串,请参阅this Stack Overflow answer。然后,您可以使用您的代码进行上传。

换种方式

您可以直接上传了以下这样一个形象:

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