在iOS / Objective-C上的一个请求中将字符串和图像,音频,视频发送到服务器
问题描述:
I want to send information as well as multimedia files (if found). All are saved in both NSString and NSData, with a single HTTP request. Information and multimedia files are not appended successfully in the body. I can send the information successfully, but I can't send the multimedia files with it in a single HTTP request.
iOS file
//My iOS code
-(void)uploadToServer {
NSDate *date = [[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-YYYY HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:date];
NSURL *postURL = [NSURL URLWithString:@"my php file"];
// Create the connection
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:postURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
NSMutableURLRequest *postRequest = [[NSMutableURLRequest alloc] init];
[postRequest setURL:postURL];
// Set POST or GET HTTP request method
[postRequest setHTTPMethod:@"POST"];
NSString *stringBoundary = @"ghkyreñnhjfhdj-74f5f-gfg5-gggff";
// Header value
NSString *headerBoundary = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", stringBoundary];
// Set header
[postRequest addValue:headerBoundary forHTTPHeaderField:@"Content-Type"];
// Create data
NSMutableData *postBody = [NSMutableData data];
// "value1" part
[postBody appendData:[[NSString stringWithFormat:@"-%@
", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Disposition: form-data; name=\"value1\"
" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"value1" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"
" dataUsingEncoding:NSUTF8StringEncoding]];
// "value2" part
[postBody appendData:[[NSString stringWithFormat:@"-%@
", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Disposition: form-data; name=\"value2\"
" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"value2" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"
" dataUsingEncoding:NSUTF8StringEncoding]];
// "value3" part
[postBody appendData:[[NSString stringWithFormat:@"-%@
", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Disposition: form-data; name=\"value3\"
" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"value3" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"
" dataUsingEncoding:NSUTF8StringEncoding]];
// Add more data here
// Add image from picker view and convert UIImage to NSData
//NSData *imageData = UIImageJPEGRepresentation(image.image, 90);
[postBody appendData:[[NSString stringWithFormat:@"-%@
", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"%@.jpg\"
", dateString]dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Type: image/jpeg
" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Transfer-Encoding: binary
" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[NSData dataWithData:image]];
// Add it to the body
[postBody appendData:image];
[postBody appendData:[@"
" dataUsingEncoding:NSUTF8StringEncoding]];
// Final boundary
[postBody appendData:[[NSString stringWithFormat:@"-%@-
", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
// Add the body to post
[postRequest setHTTPBody:postBody];
[request setTimeoutInterval:30];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * rcvdata = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (rcvdata != nil)
{
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success" message:returnString delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
NSLog(@"Return String= %@", returnString);
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failed" message:@"Check your internet connection" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
}
}
PHP file
//My PHP file is like this:
<?php
// Check for proper request
if (isset($_POST['value1'])) {
$value1 = $_POST['value1'];
$value2 = $_POST['value2'];
$value3 = $_POST['value3'];
// Insert data into the info table
$query = "INSERT INTO `info` (`value1`, `value2`, `value3) VALUES ('$value1', '$value2', '$value3')";
$result = mysql_query($query);
if ($result) {
echo "Successfully sent your data!
";
$target_path = "multimedia/";
// Check for image
$prefix="X". time();
if (isset($_FILES['image']['name'])) {
$target_path1 = $target_path . basename($prefix.$_FILES['image']['name']);
try {
if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path1)) {
throw new Exception('Could not move file');
}
else {
insertMultimedia($value1, 3, $prefix.$_FILES['image']['name'], "Image Uploaded!
", "image Not Uploaded!
");
}
}
catch (Exception $ex) {
echo "Image Not Uploaded!
";
}
}
// Check for audio
if (isset($_FILES['audio']['name'])) {
$target_path2 = $target_path . basename($prefix.$_FILES['audio']['name']);
try {
if (!move_uploaded_file($_FILES['audio']['tmp_name'], $target_path2)) {
throw new Exception('Could not move file');
}
else {
insertMultimedia($value1, 2, $prefix.$_FILES['audio']['name'], "Audio Uploaded!
", "Audio Not Uploaded!
");
}
}
catch (Exception $ex) {
echo "Audio Not Uploaded!
";
}
}
// Check for video
if (isset($_FILES['video']['name'])) {
$target_path3 = $target_path . basename($prefix.$_FILES['video']['name']);
try {
if (!move_uploaded_file($_FILES['video']['tmp_name'], $target_path3)) {
throw new Exception('Could not move file');
}
else {
insertMultimedia($value1, 1, $prefix.$_FILES['video']['name'], "Video Uploaded!
", "Video Not Uploaded!
");
}
}
catch (Exception $ex) {
echo "Video Not Uploaded exception!
";
}
}
}
}
else {
echo "Sending Failure!";
}
}
else {
echo 'Invalid Request';
}
?>
答
i use AFNetworking and this is working
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"value1": @"value1",
@"value2": @"value2",
@"value3": @"value1",
};
// BASIC AUTH (if you need):
manager.securityPolicy.allowInvalidCertificates = YES;
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"foo" password:@"bar"];
// BASIC AUTH END
NSString *URLString = @"php file";
/// !!! only jpg, have to cover png as well
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
[manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (image) {
[formData appendPartWithFileData:image name:@"image" fileName:[NSString stringWithFormat:@"%@.jpg",dateString] mimeType:@"image/jpeg"];
NSLog(@"image: %@",image);
}
if (video) {
[formData appendPartWithFileData:video name:@"video" fileName:[NSString stringWithFormat:@"%@.mp4",dateString] mimeType:@"video/quicktime"];
NSLog(@"video: %@",video);
}
if (audio) {
[formData appendPartWithFileData:audio name:@"audio" fileName:[NSString stringWithFormat:@"%@.mp3",dateString] mimeType:@"audio/m4a"];
NSLog(@"audio: %@",audio);
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Failure" message:@"Sending Failure" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
NSLog(@"Failure %@, %@", error, operation.responseString);
}];
[self dismissViewControllerAnimated:NO completion:nil];
hope this will work