2013-11-02 4 views
1

PHP와 Objective-C를 처음 접했으므로이 답변을 검색했지만 모든 것이 복잡해 보였습니다. 이해할 수 없었습니다. PHP를 사용하여 이미지 파일을 내 ftp 서버에 업로드하려고합니다.PHP - 스트림을 열지 못했습니다 :

<?php 
$file = basename($_FILES['userfile']['name']); 
$remote_file = basename($_FILES['userfile']['name']); 
//$remote_file = 'readme.txt'; 

// set up basic connection 
$ftp_server = "www.myurl.net"; 
$ftp_user_name = "myusername"; 
$ftp_user_pass = "mypassword"; 
$conn_id = ftp_connect($ftp_server); 

// login with username and password 
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); 

// check connection 
if ((!$conn_id) || (!$login_result)) { 
    echo "FTP connection has failed!"; 
    echo "Attempted to connect to $ftp_server for user $ftp_user_name"; 
    exit; 
} else { 
    echo "Connected to $ftp_server, for user $ftp_user_name"; 
} 
// upload a file 
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) { 
echo "successfully uploaded $file\n"; 
} else { 
echo "There was a problem while uploading $file\n"; 
} 

// close the connection 
ftp_close($conn_id); 
?> 

내 응용 프로그램에서 얻을 반환 문자열은 다음과 같습니다

다음
UIImage *myImage = [UIImage imageNamed:@"black_strip.png"]; 
    NSData *imageData = UIImagePNGRepresentation(myImage); 
    // setting up the URL to post to 
    NSString *urlString = @"http://www.myurl.net/GagVidApp/uploadProfImage.php"; 

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

    NSString *boundary = @"---------------------------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:[@"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[@"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: %@", returnString); 

내 PHP 코드 :

나는 이미지 업로드 내 응용 프로그램에서이 코드를 사용 :

returnString: Connected to www.myurl.net, for user myuser<br /> 
<b>Warning</b>: ftp_put(ipodfile.png) [<a href='function.ftp-put'>function.ftp-put</a>]: **failed to open stream: No such file or directory in** <b>/home/load2unet/domains/myurl.net/public_html/GagVidApp/uploadProfImage.php</b> on line <b>24</b><br /> 
There was a problem while uploading ipodfile.png 

나는 답을 찾으려고 노력했지만 행운이 없다. 어떤 도움이라도 대단히 감사하게 될 것입니다! 감사합니다

답변

1

Peter가 말한 것처럼 임시 파일의 전체 경로, 즉 $_FILES["userfile"]["tmp_name"]을 참조하지 않는 것이 문제라고 생각됩니다. 여기에 내가 오히려 FTP보다 move_uploaded_file을 사용하여, 과거에 사용했지만, 당신은 아마 생각 무엇을 얻을의 연주 :

<?php 

header('Content-Type: application/json'); 

$allowedExts = array("jpg", "jpeg", "gif", "png"); 
$extension = end(explode(".", $_FILES["userfile"]["name"])); 
if ((($_FILES["userfile"]["type"] == "image/gif") 
    || ($_FILES["userfile"]["type"] == "image/jpeg") 
    || ($_FILES["userfile"]["type"] == "image/png") 
    || ($_FILES["userfile"]["type"] == "image/pjpeg")) 
    && ($_FILES["userfile"]["size"] < 200000) 
    && in_array($extension, $allowedExts)) 
{ 
    if ($_FILES["userfile"]["error"] > 0) 
    { 
     echo json_encode(array("error" => $_FILES["userfile"]["error"])); 
    } 
    else 
    { 
     if (file_exists("upload/" . $_FILES["userfile"]["name"])) 
     { 
      echo json_encode(array("error" => $_FILES["userfile"]["name"] . " already exists")); 
     } 
     else 
     { 
      move_uploaded_file($_FILES["userfile"]["tmp_name"], "upload/" . $_FILES["userfile"]["name"]); 
      echo json_encode(array("success" => true, 
            "upload" => $_FILES["userfile"]["name"], 
            "type"  => $_FILES["userfile"]["type"], 
            "size"  => ($_FILES["userfile"]["size"]/1024) . " kB", 
            "stored in" => "upload/" . $_FILES["userfile"]["name"])); 
     } 
    } 
} 
else 
{ 
    echo json_encode(array("error" => "Invalid file")); 
} 
?> 

이 아마도 당신이 파일 크기 검사가 필요하지 않습니다를 (또는 200K가되지 않을 수도 있습니다 오른쪽 임계 값), 그래서 당신에게 달렸어. 그러나 프로그래밍 방식 인터페이스의 경우 JSON에서 응답 형식을 지정하므로 내 앱에서 응답을 쉽게 구문 분석 할 수 있습니다.

1

파일 업로드는 임시 폴더에 저장됩니다. 파일의 기본 이름 (basename($_FILES['userfile']['name']) 만 제공하기 때문에 파일은 현재 경로에서 검색되지만 존재하지 않습니다. 전체 경로를 입력하면 스크립트가 작동합니다.

+0

어떻게하면됩니까? 예제 코드를 좀 주시겠습니까? – tnylee

+0

시도하지는 않았지만, 대부분 ftp_put ($ connid, $ remote_file, $ _FILES [ 'userfile'] [ 'tmp_name'], FTP_ASCII)'이 효과적입니다. –

관련 문제