upload images and texts to server [closed]

前提是你 提交于 2019-12-08 06:14:56

问题


I have already gone through some codings, and I found some interrupts in uploading.

I want to upload six images to a server folder and some text to server database using ASIHTTPRequest. Any sample code please, thanks for spending time for my question.


回答1:


For uploading images to the server you need the following code:

NSURL *url = [NSURL URLWithString:@"http://www.xyz.com/UploadImage.php"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
request.requestMethod = @"POST";
NSString *fileName = @"iphone.jpg";
[request addPostValue:fileName forKey:@"name"];

// Upload an image
UIImage *img = [UIImage imageNamed:fileName];
NSData *imageData = UIImageJPEGRepresentation(img, 90);
[request setData:imageData withFileName:fileName andContentType:@"image/jpeg" forKey:@"image"];
[request setDelegate:self]; 
[request startAsynchronous];

For sending text to the server, you just need to append the text with the POST method like:

[request appendPostData:[@"This is my data" dataUsingEncoding:NSUTF8StringEncoding]];

Cheers!!!




回答2:


Here is the code for image uploading, you can use it

-(void)uploadImage

{
    UIImage *image = [UIImage imageWithName:@"sample.jpeg"]; 
    NSData *imageData = UIImageJPEGRepresentation(image, 90);
    NSURL *url = [NSURL URLWithString:@"http://your-url/upload.php"];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setDelegate:self];
    [request setData:imageData withFileName:@"myphoto.jpg" andContentType:@"image/jpeg" forKey:@"photo"];



[request startAsynchronous];

}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    // Use when fetching text data
    NSString *responseString = [request responseString];
    NSLog(@"response: %@", responseString);

    // Use when fetching binary data
    NSData *responseData = [request responseData];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
}



回答3:


For text, you can use this

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request appendPostData:[@"This is my data" dataUsingEncoding:NSUTF8StringEncoding]];
// Default becomes POST when you use appendPostData: / appendPostDataFromFile: / setPostBody:
[request setRequestMethod:@"PUT"];

Ref: http://allseeing-i.com/ASIHTTPRequest/How-to-use



来源:https://stackoverflow.com/questions/9800881/upload-images-and-texts-to-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!