将图片上传至远程服务器,iPhone

3
我希望从图库或相机中获取图片并将它们上传到远程服务器,然后获取每个已上传图片的URL。我想从零开始学习,并寻求一些关于如何入手的帮助。我需要用最简单的方式来完成这个任务,使用PHP和MySQL。我应该从哪里开始呢?另外,我不想使用任何第三方工具。只需要简单地进行数据库连接、插入和读取即可。请告诉我该怎么做。
1个回答

3

哇,我很棒!

这个人也很棒。 http://iphone.zcentric.com/2008/08/29/post-a-uiimage-to-the-web/

这是我实现的内容。

UIImage *myImage = [UIImage imageNamed:@"foo.png"];
NSData *imageData = UIImagePNGRepresentation(myImage);
// setting up the URL to post to
NSString *urlString = @"myurl/insert.php";

// setting up the request object now
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"];

/*
 now lets create the body of the post
 */
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.jpg\"\r\n"] 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]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];

// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

NSLog(returnString);

关于PHP,它看起来像是这样的。

   <?php
       $uploaddir = './uploads/';
   $file = basename($_FILES['userfile']['name']);
   $uploadfile = $uploaddir . $file;

  if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
        echo "myurl/uploads/{$file}";
      } 
?>

老板!!!@lessfame

注意,这只是将照片上传到上传文件夹。我的下一个任务是使用自定义名称,并将URL和文件名存储在数据库中。哇! - Franky
这一行代码:[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name="userfile"; filename="ipodfile.jpg"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 不起作用,<br> 调试信息:($_FILES['userfile']['name']) 为空。 - vualoaithu
那么,如果您想用一个变量来替换“ipodfile.jpg”,该怎么办呢? - Tom Tallak Solbu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接