2014-09-11 77 views
0

我想在XCODE中使用PHP將圖像上傳到MySQL數據庫,但我遇到了一些問題,因爲它不起作用。當用戶插入文本時它工作正常,但當涉及到圖像時,我無法做到。使用xcode上傳圖像(MySQL + PHP)

我已閱讀了一些教程和示例,但它們不在我的xcode項目中工作。你能幫我解決這個問題嗎?

這是我的代碼:

- (IBAction)uploadPhoto:(UIButton *)sender { 

    NSLog(@"Photo enviada"); 
    /* 
    NSString *strURL = [NSString stringWithFormat:@"http://example.com/upload.php?image=%@",_imageView.image]; 
    NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]]; 
    NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding]; 
    NSLog(@"%@", strResult); 
    */ 
    NSData *imageData = UIImageJPEGRepresentation(_imageView.image, 90); 
    NSString *urlString = @"http://autograpp.com/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"]; 

    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=\"ipodfile.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [body appendData:[NSData dataWithData:imageData]]; 
    [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]; 
} 

但我對得到一個錯誤:

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; 

ARC禁止自動釋放的明確消息發送。

在此先感謝。

+0

相應圖像字段的數據類型是什麼? – ursitesion 2014-09-11 10:28:45

+0

你好。我怎樣才能看到圖像的數據類型?再次感謝您的幫助。 – WirajPS 2014-09-12 06:13:56

+0

根據我的理解,您必須將圖像插入表格的一列。當你創建一個表時,你必須定義列的數據類型。在您必須存儲圖像的列中,請選擇數據類型爲「blob」。 要了解更多關於'blob'數據類型的信息,請參考'http:// dev.mysql.com/doc/refman/5.0/en/blob.html' – ursitesion 2014-09-12 07:04:47

回答

0

您在支持ARC的項目中使用- autorelease;這既不必要也不允許。如果您有

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 

它應該工作取代

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; 

此代碼可能是年紀大一點和預日期ARC(自動引用計數。)

在ARC中,您不必再保留/釋放對象;這是自動完成的。