将图像和文本上传到服务器

时间:2012-03-21 08:20:26

标签: iphone objective-c asihttprequest

我已经完成了一些编码,我在上传时发现了一些中断。

我想使用ASIHTTPRequest将六个图像上传到服务器文件夹,将一些文本上传到服务器数据库。 请提供任何示例代码,感谢您花时间处理我的问题。

3 个答案:

答案 0 :(得分:3)

以下是图片上传的代码,您可以使用

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

答案 1 :(得分:2)

要将图像上传到服务器,您需要以下代码:

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

要将文本发送到服务器,只需使用POST方法附加文本,如:

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

干杯!!!

答案 2 :(得分:0)

对于文字,您可以使用此

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

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