2009-05-21 194 views
1

我發現了許多有關通過Windows上的C++將文件上傳到Web服務器的示例。在Mac上通過HTTP/HTTPS和/或FTP/FTPS上傳文件

但是,我在搜索 lot(我認爲我對Google很好!)之後努力尋找任何示例來幫助我在Mac上實現相同效果。

任何人都可以指點我如何上傳文件到Mac OS上的Web服務器上使用C++或目標C?

它可以通過HTTP/HTTPS FTP/FTPS(或兩者)。

謝謝!

回答

3

您可以使用'libcurl',參見維基百科上的this article

1

你想使用一個NSURLConnection的一個NSMutableURLRequest,是這樣的:

NSMutableURLRequest *theRequest=[[NSMutableURLRequest alloc] init]; 
[theRequest addValue:@"attachment;filename=\"file2.gif\"" forHTTPHeaderField:@"Content-disposition"]; 
[theRequest addValue:@"image/gif" forHTTPHeaderField:@"Content-Type"]; 
[theRequest addValue:@"binary" forHTTPHeaderField:@"Content-Transfer-Encoding"]; 
[theRequest setHttpBody:myBodyNSDataObject]; 
// create the connection with the request 
// and start loading the data 
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 
if (theConnection) { 
    // Create the NSMutableData that will hold 
    // the received data 
    // receivedData is declared as a method instance elsewhere 
    receivedData=[[NSMutableData data] retain]; 
} else { 
    // inform the user that the download could not be made 
} 

可以修改或使用NSMutableURLRequest方法設置頭:

- (void)addValue:(NSString *)value forHTTPHeaderField:(NSString *)field 

響應將是服務器返回的任何內容。您可以查看Apple's documentation以瞭解其他委託方法的實施情況,以獲取回覆的主體。你應該有NSData對象表示你想要上傳的文件的內容。使用FTP做同樣的事情會涉及更多的內容,但是這將用於發佈文件體。您將要確保你的NSData對象的設置類似於一個HTTP POST的身體,這樣你設置像頭:

[theRequest addValue:@"attachment;filename=\"file2.gif\"" forHTTPHeaderField:@"Content-disposition"]; 
[theRequest addValue:@"image/gif" forHTTPHeaderField:@"Content-Type"]; 
[theRequest addValue:@"binary" forHTTPHeaderField:@"Content-Transfer-Encoding"]; 

然後你應該追加身體。在服務器端,您可以獲取文件名和組成文件的字節。

這不完全是你應該使用的代碼,但它應該給你一個好主意如何繼續。