简体   繁体   English

如何在iOS上将图像作为JSON从库上传到服务器

[英]How to upload image to server from gallery as JSON on iOS

How can I upload an image to a server from the gallery on iPhone as JSON? 如何从iPhone上的库中将图像作为JSON上传到服务器? I tried the following: 我尝试了以下方法:

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

if you want to upload an image as a string you must convert your image data to Base64, then you can use your above method:- 如果您想将图像上传为字符串,则必须将图像数据转换为Base64,然后您可以使用上述方法: -

For converting to a base64 string, refer to this Stack Overflow answer . 要转换为base64字符串,请参阅此Stack Overflow答案 You can then use your code for uploading. 然后,您可以使用代码进行上传。

Another Way 其他方式

You can directly upload an image like so: 您可以直接上传图片,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM