Я пытался выяснить, как загрузить изображение на мой php-сервер с NSUrlSessionUploadTask в obj-c, но не могу заставить его работать. Я пытаюсь отправить параметр «longID» и изображение JPG с multipart / form-data.
//User has confirmed that bilagImage should be used. Now, set up an NSURLSession for posting the image to the php server.NSString *boundary = @"3kam891boundaryKey28438981";NSMutableData *bodyData = [[NSMutableData alloc] init];
//feed the NSMutableData object with a boundary followed by the longID and then yet another boundary
[bodyData appendData:[[NSString stringWithFormat: @"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; //Add first boundary
[bodyData appendData:[@"Content-Disposition: form-data; name=\"longID\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; //Add description of longID
[bodyData appendData:[longID dataUsingEncoding:NSUTF8StringEncoding]]; //Add the longID
[bodyData appendData:[[NSString stringWithFormat: @"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; //Add boundary//add the image
[bodyData appendData:[@"Content-Disposition: form-data; name=\"fileToUpload\"; filename=\"image.jpg\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; //Add description
NSData *imageData = UIImageJPEGRepresentation(bilagImage, 0.6); //Turn image into NSData
[bodyData appendData:imageData];
[bodyData appendData:[[NSString stringWithFormat: @"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; //Add boundary//add the submit parameter
[bodyData appendData:[@"Content-Disposition: form-data; name=\"submit\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; //Add description of submit
[bodyData appendData:[@"Upload Image" dataUsingEncoding:NSUTF8StringEncoding]]; //Add content of submit
[bodyData appendData:[[NSString stringWithFormat: @"\r\n--%@--", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; //Add last boundary
NSLog(@"RESULTAT: %@", [NSString stringWithUTF8String:[bodyData bytes]]);// Setup the session
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.HTTPAdditionalHeaders = @{
@"Accept" : @"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
@"Content-Type" : [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]
};
// Create the session
// We can use the delegate to track upload progress
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];NSString *postURLString = @"mywebsite";
NSURL *postURL = [NSURL URLWithString:postURLString];NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:postURL];
request.HTTPMethod = @"POST";
request.HTTPBody = bodyData;NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:bodyData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// Process the response
NSLog(@"response %@", [NSString stringWithUTF8String:[data bytes]]);
}];
[uploadTask resume];
Сервер выдает «Извините, произошла ошибка при загрузке вашего файла».
PHP-код:
$target_dir = "uploads/";
$target_file = $target_dir . $_POST["longID"] . ".jpg";
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Already exists, delete old.";
unlink($target_file);
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 3000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
}
// if everything is ok, try to upload file
else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
Задача ещё не решена.
Других решений пока нет …