本文介绍了无法使用Alamofire在SWIFT 3中上传图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试让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)
            }
        }
    )

这应该会将图像上载到服务器,但是我不知道如何正确地将图像保存到服务器上。服务器实际上并不需要该文件的任何信息,因为它将为它生成一个新名称。然后,它应该将该名称发送回应用程序。

我知道如何在SWIFT 3和php中处理JSON,因为我以前这样做过。我还确信至少有一些内容会上载到服务器,因为我已经拿回了一些基本信息。

下面的PHP代码几乎肯定不是很好,但它主要是一个测试。

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

// sanitize filename
$fileName = preg_replace("([^wsd-_~,;:[]().])", '', $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);
?>

提前感谢您的帮助:)

附注:我刚接触斯威夫特,所以请温柔点;)

推荐答案

好的,所以。我想通了。原来,Alamofire使用php的$_FILES函数。没有提到这一点,所以让我来试着把事情弄清楚。以下是带注释的完整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)
                }
            }
        )

我希望这能帮助很多有同样问题的人!如果有什么遗失或您想知道的,请告诉我!

这篇关于无法使用Alamofire在SWIFT 3中上传图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-17 00:15