не удается загрузить изображение в Swift 3, используя Alamofire для работы

Я застрял на три дня, пытаясь заставить Alamofire загрузить изображение. Идея состоит в том, что Alamofire отправит его на сервер с некоторым php-кодом. После многих попыток и поиска в разных местах часть кода должна работать, но документация на стороне сервера для Alamofire ужасна.

Недавнее обновление для swift 3 не поможет многим ответить мудро …

Вот мой код Swift 3:

let imageData = UIImageJPEGRepresentation(imageFile!, 1)!

Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(imageData, withName: "image", fileName: "image.jpeg", mimeType: "file/jpeg")
},
to: "https://someadress.com/post/upload.php",
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
}
)

Это должно загрузить изображение на сервер, но я понятия не имею, как правильно получить изображение, сохраненное на сервере. Серверу на самом деле не нужна информация о файле, поскольку он сгенерирует для него новое имя. Затем следует отправить это имя обратно в приложение.

Я знаю, как обрабатывать JSON в Swift 3 и php, так как я делал это раньше. Я также точно знаю, что по крайней мере что-то загружается на сервер, так как я получил некоторую основную информацию обратно.

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

<?php
// get the file data
$fileData = file_get_contents('php://input');

// sanitize filename
$fileName = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).])", '', $fileData);
// save to disk

$fileLocation = "../images/" . $fileName;
file_put_contents($fileLocation, $fileData);

if (empty($fileData)) {
$response = array("error" => "no data");
}
else {
$response = array("error" => "ok " . $fileName);
}

echo json_encode($response);
?>

Спасибо за любую помощь заранее 🙂

постскриптум Я новичок в стремительности, поэтому, пожалуйста, будьте нежны;)

1

Решение

Ладно ооочень Я понял. Оказывается, Alamofire использует $_FILES функция php. Там нет никакого упоминания об этом, поэтому позвольте мне попытаться прояснить ситуацию. Вот полный код PHP с комментариями.

<?php

// If the name of the image is not in this array, the app didn't post anything.
if (empty($_FILES["image"])) {
// So we send a message back saying there is no data...
$response = array("error" => "nodata");
}
// If there is data
else {
$response['error'] = "NULL";
// Setup a filename for the file. Uniqid can be changed to anything, but this makes sure
// that every file doesn't overwrite anything existing.
$filename = uniqid() . ".jpg";
// If the server can move the temporary uploaded file to the server
if (move_uploaded_file($_FILES['image']['tmp_name'], "../images/" . $filename)) {
// Send a message back saying everything worked!
// I also send back a link to the file, and the name.
$response['status'] = "success";
$response['filepath'] = "[APILINK]/images/" . $filename;
$response['filename'] = "".$_FILES["file"]["name"];

} else{
// If it can't do that, Send back a failure message, and everything there is / should be form the message
// Here you can also see how to reach induvidual data from the image, such as the name.
$response['status'] = "Failure";
$response['error']  = "".$_FILES["image"]["error"];
$response['name']   = "".$_FILES["image"]["name"];
$response['path']   = "".$_FILES["image"]["tmp_name"];
$response['type']   = "".$_FILES["image"]["type"];
$response['size']   = "".$_FILES["image"]["size"];
}
}

// Encode all the responses, and echo them.
// This way Alamofire gets everything it needs to know
echo json_encode($response);
?>

Вот и все. Все, что вам нужно сделать, это убедиться, что имя, которое вы отправляете с запросом Alamofire, совпадает с именем в скобках ‘$ _FILES’. Временное имя — это имя файла в Alamofire.

Вот код Swift 3.

// Note that the image needs to be converted to imagedata, in order to work with Alamofire.
let imageData = UIImageJPEGRepresentation(imageFile!, 0.5)!

Alamofire.upload(
multipartFormData: { multipartFormData in
// Here is where things would change for you
// With name is the thing between the $files, and filename is the temp name.
// Make sure mimeType is the same as the type of imagedata you made!
multipartFormData.append(imageData, withName: "image", fileName: "image.jpg", mimeType: "image/jpeg")
},
to: "[APILINK]/post/upload.php",
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if let result = response.result.value {
// Get the json response. From this, we can get all things we send back to the app.
let JSON = result as! NSDictionary
self.imageServerLocation = JSON.object(forKey: "filepath") as? String
debugPrint(response)
}
}
case .failure(let encodingError):
print(encodingError)
}
}
)

Я надеюсь, что это помогает многим людям, которые имеют ту же проблему! Дайте мне знать, если чего-то не хватает или что-то, что вы хотите знать!

6

Другие решения

Свифт 3

 func uploadImage(_ imageFileUrl:URL, encodeCompletion: ((Alamofire.SessionManager.MultipartFormDataEncodingResult) -> Void)?){
let fileName = "imageName.jpg"let headers = ["contentType":"image/jpeg"]
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageFileUrl, withName: fileName)
}, to: "uploadPath", method: .post, headers: headers, encodingCompletion: encodeCompletion)
}
0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector