2013-07-15 3 views
-3

Я действительно устал, ища здесь и в google, но плохой результат.Файл POST SQLITE на удаленный сервер

прошу, если я хочу, чтобы загрузить файл SQLITE в документах/локальную к серверу

, как я мог бы сделать это с прошивкой, чтобы сделать некоторые из резервной копии базы данных

Ваш ответ будет высоко оценен.

+0

Итак, вы спрашиваете, как передать содержимое произвольного файла в качестве полезной нагрузки HTTP? – SLaks

+0

@SLaks Я так думаю, мне нужно отправить name.sqlite на мой сервер, который name.sqlite в пути к документу для iDevice – SimpleojbC

+0

Существует много информации о stackoverflow и Интернете о том, как открыть NSURLConnection и данные POST на сервере , –

ответ

0

Используйте multipart/form-data для заголовка Content-Type и Content-Type: application/octet-stream для файла в теле HTTP.

ОК, я покажу иа демо, просто создать новый Xcode проект с шаблоном 'Empty Application', проверьте 'Use ARC', а затем вставьте:

#import "AppDelegate.h" 

@interface AppDelegate() 
@property (nonatomic, strong) NSURLConnection *urlConnection; 
@property (nonatomic, strong) NSMutableData *receivedData; 
@end 

@implementation AppDelegate 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
     [self.window makeKeyAndVisible]; 
     NSString *localFile = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) 
           objectAtIndex:0] stringByAppendingPathComponent:@"user.sqlite"]; 
     NSString *api = @"http://192.168.0.170/test/upload/upload.php"; 
     [self sendFile:localFile toServer:api]; 
     return YES; 
} 

- (void)sendFile:(NSString *)filePath toServer:(NSString *)serverURL 
{ 
     NSData *fileData = [NSData dataWithContentsOfFile:filePath]; 
     if (!fileData) { 
       NSLog(@"Error: file error"); 
       return; 
     } 

     if (self.urlConnection) { 
       [self.urlConnection cancel]; 
       self.urlConnection = nil; 
     } 

     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] 
             initWithURL:[NSURL URLWithString:serverURL]]; 
     [request setTimeoutInterval:30.0]; 
     [request setHTTPMethod:@"POST"]; 
     NSString *boundary = @"780808070779786865757"; 

     /* Header */ 
     NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; 
     [request addValue:contentType forHTTPHeaderField:@"Content-Type"]; 

     /* Body */ 
     NSMutableData *postData = [NSMutableData data]; 
     [postData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
     [postData appendData:[[NSString stringWithFormat:@"Content-Disposition:form-data; name=\"file\"; filename=\"test.sqlite\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
     [postData appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
     [postData appendData:fileData]; 
     [postData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
     [request setHTTPBody:postData]; 

     self.urlConnection = [NSURLConnection connectionWithRequest:request delegate:self]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
     if (self.receivedData) { 
       self.receivedData = nil; 
     } 
     self.receivedData = [[NSMutableData alloc] init]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
     [self.receivedData appendData:data]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
     NSLog(@"finish requesting: %@", [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding]); 
     self.urlConnection = nil; 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
     NSLog(@"requesting error: %@", [error localizedDescription]); 
     self.urlConnection = nil; 
} 

@end 

и на стороне сервера, PHP:

<?php 

$uploaddir = './uploads/'; 

if(!file_exists($uploaddir)) @mkdir($uploaddir); 
$file = basename($_FILES['file']['name']); 
$uploadfilename = rand() . '-' . $file; 
$uploadfile = $uploaddir . $uploadfilename; 
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) { 
     $fileURL = "http://192.168.0.170/test/upload/uploads/{$uploadfilename}"; 
     // echo '<a href=' . $fileURL . '>' . $fileURL . '</a>'; 
     $jsonArray = array( 
       'status' => 1, 
       'url' => $fileURL, 
     ); 
     echo json_encode($jsonArray); 
} else { 
     echo json_encode(array('status' => -1)); 
} 
+0

Я попробую и ответ скоро. Спасибо заранее – SimpleojbC

Смежные вопросы