2011-03-14 87 views
1

我剛剛開始使用xcode業務,目前爲止這麼好,除了這個小細節:我不知道如何將UIImage發佈到網絡。過去3天我一直在嘗試一切(閱讀和查詢很多),但沒有成功。答案是,我認爲是在我的鼻子下面,仍然...沒有運氣。在網絡上發佈UIImage

我離開這裏我寫的代碼(無論是在Objective-C和PHP):它根本不工作!沒有圖像上傳。請,有人可以幫我嗎?

//目標-C

NSData *theData = UIImagePNGRepresentation(photo.image); 
NSString *urlString = @"http://www.testes01.com/newsie/receberprofilephoto.php"; 
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"]; 
NSMutableData *body = [NSMutableData data]; 
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"file\"; filename=\"iphoneimage.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
[body appendData:[NSData dataWithData:theData]]; 
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
[request setHTTPBody:body]; 
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; 

// PHP

move_uploaded_file($_FILES["file"][tmp_name], "fotosprofile/" . $_FILES["file"]["name"]); 

預先感謝。

+0

這有效,唯一錯誤的不是CHMODing文件夾到777,所以你可以讀寫。 – jcrowson 2012-07-11 09:03:36

回答

1

這裏是一個Web self.image的圖片上傳的代碼是我所製作的特性和合成it.Get你的形象在self.image然後我UIImage對象: -

NSData *imagedata=[NSData dataWithData:UIImagePNGRepresentation(self.image)]; 
    NSString *base64string=[imagedata base64EncodedString]; 
    NSString *str = [NSString stringWithFormat:@"http://www.testes01.com/newsie/receberprofilephoto.php"]; 
    NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; 
    [request setPostValue:base64string forKey:@"imagedata"]; 
    [request setRequestMethod:@"POST"]; 
    [request setDelegate:self]; 
    [request startSynchronous]; 
    NSLog(@"responseStatusCode %i",[request responseStatusCode]); 
    NSLog(@"responseStatusString %@",[request responseString]); 

希望這可能會幫助你!

+1

嗨@Jenifer,謝謝你的及時回覆。不幸的是,我也嘗試過使用ASIHTTPRequest庫,但它也沒有工作。不過,我注意到幾個小時前,我發佈圖像的服務器不允許我以編程方式上傳圖像;我嘗試了chmod 777,但我沒有權限。所以,我打電話給他們解決了我的問題。底線,代碼沒問題。對於什麼是值得的,感謝您的回覆,也許爲了繁榮,代碼保持在這裏。只要記住,如果代碼不起作用,問題可能與您的文件夾或文件權限有關。再見! – 2011-03-15 21:01:45