![](/img/trans.png)
[英]AFNetworking 2.0 POST + PHP block failure called although upload is successful
[英]POST jpeg upload with AFNetworking
我不能為我的生活弄清楚為什么當我使用AFNetworking時這不起作用。 它與ASIHTTP合作。 這對我來說都很新鮮。 但我無法弄清楚為什么這些文件不再從$ _FILES傳輸到服務器的HD了。 這是iOS代碼:
- (IBAction)uploadPressed
{
[self.fileName resignFirstResponder];
NSURL *remoteUrl = [NSURL URLWithString:@"http://mysite.com"];
NSTimeInterval timeInterval = [NSDate timeIntervalSinceReferenceDate];
NSString *photoName=[NSString stringWithFormat:@"%lf-Photo.jpeg",timeInterval];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:photoName];
NSData * photoImageData = UIImageJPEGRepresentation(self.remoteImage.image, 1.0);
[photoImageData writeToFile:filePath atomically:YES];
NSLog(@"photo written to path: e%@", filePath);
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:remoteUrl];
NSMutableURLRequest *afRequest = [httpClient multipartFormRequestWithMethod:@"POST"
path:@"/photos"
parameters:nil
constructingBodyWithBlock:^(id <AFMultipartFormData>formData)
{
[formData appendPartWithFormData:[self.fileName.text dataUsingEncoding:NSUTF8StringEncoding]
name:@"name"];
[formData appendPartWithFileData:photoImageData
name:self.fileName.text
fileName:filePath
mimeType:@"image/jpeg"];
}
];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:afRequest];
[operation setUploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
NSLog(@"Sent %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation setCompletionBlock:^{
NSLog(@"%@", operation.responseString); //Gives a very scary warning
}];
[operation start];
}
我曾經這樣做過:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:remoteUrl];
[request setPostValue:self.fileName.text forKey:@"name"];
[request setFile:filePath forKey:@"filename"];
[request setDelegate:self];
[request startAsynchronous];
這是我的PHP:
{
// these could be stored in a .ini file and loaded
// via parse_ini_file()... however, this will suffice
// for an example
$codes = Array(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => '(Unused)',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported'
);
return (isset($codes[$status])) ? $codes[$status] : '';
}
function sendResponse($status = 200, $body = '', $content_type = 'text/html')
{
$status_header = 'HTTP/1.1 ' . $status . ' ' . getStatusCodeMessage($status);
header($status_header);
header('Content-type: ' . $content_type);
echo $body;
}
if (!empty($_FILES) && isset($_POST["name"])) {
$name = $_POST["name"];
$tmp_name = $_FILES['filename']['tmp_name'];
$uploads_dir = '/var/www/cnet/photos';
move_uploaded_file($tmp_name, "$uploads_dir/$name.jpg");
$result = array("SUCCEEDED");
sendResponse(200, json_encode($result));
} else {
sendResponse(400, 'Nope');
}
?>
試試這段代碼:
NSData* sendData = [self.fileName.text dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *sendDictionary = [NSDictionary dictionaryWithObject:sendData forKey:@"name"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:remoteUrl];
NSMutableURLRequest *afRequest = [httpClient multipartFormRequestWithMethod:@"POST"
path:@"/photos"
parameters:sendDictionary
constructingBodyWithBlock:^(id <AFMultipartFormData>formData)
{
[formData appendPartWithFileData:photoImageData
name:self.fileName.text
fileName:filePath
mimeType:@"image/jpeg"];
}
];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:afRequest];
[operation setUploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
NSLog(@"Sent %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation setCompletionBlock:^{
NSLog(@"%@", operation.responseString); //Gives a very scary warning
}];
[operation start];
我不太熟悉ASI使用setPostValue:forKey:
執行的setPostValue:forKey:
,但是您可能缺少要從圖像上載單獨發送的name
參數。
客戶端或服務器的確切記錄是什么? 進度塊是否記錄?
其他幾點:
[operation start]
; 不需要為此創建操作隊列。 operation
設置completionBlock
,使用響應的NSLog
或類似的東西。 AFHTTPClient
基類以返回單例實例,例如AFNetworking示例應用程序中的Gowalla API客戶端。 然后,該客戶端可以管理所有網絡請求的單個操作隊列。 我有一個使用NSMutableURLRequest的解決方法:
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:remoteUrl];
[req setHTTPMethod:@"POST"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data, boundary=%@", boundary];
[req setValue:contentType forHTTPHeaderField:@"Content-type"];
//adding the body:
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Disposition: form-data; name=\"name\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[name dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Disposition: form-data; name=\"filename\";\r\nfilename=\"china.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[NSData dataWithData:imageData]];
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[req setHTTPBody:postBody];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.