2009-12-21 86 views
10

我發現從在線上的圖片從iPhone上傳圖片到服務器文件夾,其顯示使用服務器端腳本例如。使用PHP在服務器端從iphone上傳圖片到服務器文件夾

<?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!"; 
} 
/> 

是任何possibilites直接上傳圖片到服務器上的文件夾沒有上面的代碼,

讓的說我要上傳到http://111.22.333.44/mysite/pics/瓦特/ O任何服務器端腳本,如果如何可以做到這一點

感謝

回答

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

這個代碼將會對你有所幫助....

+0

我不得不刪除與應用行/ octet-讓它與attachment_fu一起工作。任何想法爲什麼? – 2011-04-23 14:09:05

+0

這是偉大的代碼。第一次爲我工作。謝謝parvind :) – Prerna 2011-07-28 11:50:11

+0

請注意上傳文件的大小。你正在創建內存中整個文件內容的請求,然後發送它......如果文件太大(或者你併發地上傳了很多文件),你可能會遇到內存消耗問題 – JakubKnejzlik 2014-07-23 03:08:40

0

如果你設置你的網站服務器允許PUT方法可以做到這一點。 99%的Web服務器只允許GET和POST方法。

從來沒有這樣做,我不能給你很多幫助。這裏是一個網頁,我從谷歌得到了談論它:

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