将iPhone中的图片上传到服务器文件夹

10

我在网上找到了一些代码片段,可以将iPhone上的图片上传到服务器文件夹,其中显示需要使用服务器端脚本,例如在服务器端使用PHP。

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

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
        echo "Uploaded!";
}else{
   echo "Not Uploaded!";
}
/>

是否可以直接将图片上传到服务器文件夹而不需要使用上面的代码呢?

假设我想在没有服务器端脚本的情况下上传到http://111.22.333.44/mysite/pics/,如果可以,如何实现?

2个回答

18
/*
  turning the image into a NSData object
  getting the image back out of the UIImageView
  setting the quality to 90
 */
 NSData *imageData = UIImageJPEGRepresentation(image.image, 90);
 // setting up the URL to post to
 NSString *urlString = @"http://iphone.zcentric.com/test-upload.php";

 // setting up the request object now
 NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
 [request setURL:[NSURL URLWithString:urlString]];
 [request setHTTPMethod:@"POST"];

 /*
  add some header info now
  we always need a boundary when we post a file
  also we need to set the content type

  You might want to generate a random boundary.. this is just the same 
  as my output from wireshark on a valid html 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);

这段代码将对您有所帮助...


我不得不删除带有application/octet-stream的那一行,才能让它与attachment_fu一起正常工作。你有什么想法为什么会这样? - James Testa
这是很棒的代码。第一次就为我工作了。谢谢 Parvind :) - Prerna
请注意上传文件的大小。您正在使用整个文件内容创建请求,然后发送它...如果文件太大(或您同时上传多个文件),您可能会遇到内存消耗问题。 - JakubKnejzlik

0

如果你设置了你的 Web 服务器以允许 PUT 方法,你就可以这样做。99% 的 Web 服务器只允许 GET 和 POST 方法。

我从未这样做过,无法提供太多帮助。这是我从谷歌上找到的一篇文章,其中讨论了此问题:

http://www.w3.org/QA/2008/10/understanding-http-put.html


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