将.txt文件提交到Web服务

时间:2014-09-08 12:46:39

标签: ios objective-c iphone web-services file

请帮助.. 我试图将.txt文件上传到网络服务..有什么想法吗?

这里我是如何将数据发送到网络服务的

    self.responseData=[[NSMutableData alloc]initWithLength:0];


    NSString *tempString=[[NSString alloc]initWithFormat:@"%@",Register_URL];


    NSURL *url = [NSURL URLWithString:[tempString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
    (void)[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];

1 个答案:

答案 0 :(得分:0)

刚刚找到解决方案..希望它能帮助任何人:)

NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullFilePath = [documentsDirectory stringByAppendingPathComponent:yourFileName.txt];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

NSData *fileData = [[NSFileManager defaultManager] contentsAtPath: fullFilePath];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"yourServiceURL"]];
[request setHTTPMethod:@"POST"];

NSString *boundary = @"---------------------------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",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[@"Content-Disposition: form-data; name=\"userfile\"; filename=\"yourFileName.txt\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[NSData dataWithData:fileData]];

[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];
    dispatch_async(dispatch_get_main_queue(),^ {
        [self LogResult:returnString];
    });
});

在你的类中的某个地方实现“LogResult:”方法。