php - 无法使用 Alamofire 在 swift 3 中上传图片

标签 php json swift3 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)
            }
        }
    )

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

我知道如何在 Swift 3 和 php 中处理 JSON,因为我以前做过。我也确信至少有一些东西被上传到服务器,因为我已经得到了一些基本信息。

下面的 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);
?>

提前感谢您的帮助:)

附注我是 swift 的新手,所以请保持温柔 ;)

最佳答案

好的,太棒了。我想到了。原来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)
                }
            }
        )

希望对遇到同样问题的人有所帮助!如果有任何遗漏或您想知道的任何信息,请告诉我!

关于php - 无法使用 Alamofire 在 swift 3 中上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40348190/

相关文章:

ios - 从 Swift 2.3 更新到 Swift 3.0 后类协议(protocol)不起作用

php - 向 Laravel 中的选择查询添加一个具有值的新列

php - Facebook SDK v4 和 Graph Api 2.x 在粉丝页面墙中自动发布

java - 添加对 JSON 结构的更改

javascript - 从 json 数组动态创建和嵌套 DIV 项

ios - Xcode安装prev Swift版本

swift - 在 Swift 的 UITableView 单元格中添加开关

php - 仅 PHP 的 "cache engine"值得吗?

php - Symfony2 : Repository's findAll() returns multiple instances of same entity instead of all entities

arrays - 快速发送数组到Web服务参数