如何将文件上传到服务器?

时间:2012-05-21 12:24:59

标签: iphone

这是我从支持文件上传txt文件的代码;

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"serverIP" ofType:@"txt"];  
    NSData *myData = [NSData dataWithContentsOfFile:filePath];  
    NSLog(@"data %@",myData);

    //url for the server
    NSString *urlString = @"http://192.168.2.111/myupload/upload.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"];

    /*
     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=\"serverIP.txt\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:myData]];
    [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,因为我面临很多问题。

没有毛利克,也许我的解释还不够让我举个例子。假设我有一个名为file.txt的文件,其大小为30MB,当我读取文件的包含时,它将给我所有30MB包含的文件。在sendSynchronousRequest方法中,我想要提供高达10mb的数据请求和老化调用相同的东西,除非它到达文件的最后一个点。 (简而言之,我想使用循环将请求部分发送到服务器)

0 个答案:

没有答案