我正在尝试将图片从我的应用上传到我的服务器。我正在学习本教程(http://zcentric.com/2008/08/29/post-a-uiimage-to-the-web/)。当我从教程中复制代码时,我得到了一堆警告和错误,所以我修改了它,如下所示。
正在调用uploadImage方法,twitterImage包含正确的照片,但图像未上传到user_photos目录。任何建议都会很棒!
这是我的应用代码:
-(void)uploadImage {
NSData *imageData = UIImageJPEGRepresentation(twitterImage, 90);
NSString *urlString = @"http://website.com/user_photo_upload.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------673864587263478628734";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data;
boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"rn--%@rn",boundary]
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data;name=\"userfile\";
filename=\"ipodfile.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-streamrnrn"
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"rn--%@--rn",boundary]
dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData
encoding:NSUTF8StringEncoding];
}
这是我的user_photo_upload.php文件:
<?php
$uploaddir = '../user_photos/';
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir . $file;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "http://website.com/user_photos/{$file}";
}
?>
答案 0 :(得分:0)
在我的建议中,您可以使用 ASIHTTPRequest 框架将图像上传到服务器。您可以从here下载框架。这很容易理解。
请参阅以下有关使用ASIHTTPRequest上传图像的代码
NSData *imgData = UIImageJPEGRepresentation(IMAGE, 0.9);
formReq = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlString]];
formReq.delegate = self;
[formReq setPostValue:VAL1 forKey:KEY1];
if (imgData) {
[formReq setData:imgData withFileName:[NSString stringWithFormat:@"ipodfile.jpg"] andContentType:@"image/jpeg" forKey:@"userfile"];
}
[formReq startSynchronous];
您还可以参考一个很好的教程here
答案 1 :(得分:0)
如果您想从NSMutableURLRequest
移出,那么最好的选择是AFNetworking
获取from here
ASIHTTPRequest
未被维护,不应按照library here的开发人员的说法使用
图片上传示例
-(void)call
{
//the image name is Denise.jpg i have uses image you can youse any file
//just convert it to nsdat in an appropriateway
UIImage *image= [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Denise" ofType:@"jpg"]];
// getting data from image
NSData *photoData= UIImagePNGRepresentation(image);
// making AFHttpClient
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"your url string"]];
//setting headers
[client setDefaultHeader:@"multipart/form-data; charset=utf-8; boundary=0xKhTmLbOuNdArY" value:@"Content-Type"];
[client setDefaultHeader:@"key" value:@"value"];
NSMutableURLRequest *request1 = [client multipartFormRequestWithMethod:@"POST" path:@"application/uploadfile" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
//setting body
[formData appendPartWithFormData:[[NSString stringWithFormat:@"Value"] dataUsingEncoding:NSUTF8StringEncoding] name:@"Key"];
[formData appendPartWithFormData:[[NSString stringWithFormat:@"Value"] dataUsingEncoding:NSUTF8StringEncoding] name:@"Key"];
//...
[formData appendPartWithFileData:photoData name:@"file_data" fileName:@"file.png" mimeType:@"image/png"];
}];
[request1 setTimeoutInterval:180];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request1];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
float progress = totalBytesWritten / (float)totalBytesExpectedToWrite;
// use this float value to set progress bar.
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *jsons = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
NSLog(@"%@",responseObject);
NSLog(@"response headers: %@", [[operation response] allHeaderFields]);
NSLog(@"response: %@",jsons);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
if([operation.response statusCode] == 403)
{
NSLog(@"Upload Failed");
return;
}
NSLog(@"error: %@", [error debugDescription]);
}];
[operation start];
}
答案 2 :(得分:0)
当您将图像附加到正文时,内容处置应该是附件而非表单数据,就在您将图像数据附加到正文之前。所以替换以下代码:
[body appendData:[@"Content-Disposition: form-data;name=\"userfile\";
filename=\"ipodfile.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
用这个:
[body appendData:[@"Content-Disposition: attachment;name=\"userfile\";
filename=\"ipodfile.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];