【问题标题】:Alamofire upload via .POST to PHP. Where is the uploaded file?Alamofire 通过 .POST 上传到 PHP。上传的文件在哪里?
【发布时间】:2015-08-17 23:56:54
【问题描述】:

我使用 .upload 方法上传到我服务器上的 php 文件,它似乎可以工作(我收到 200 响应)

upload(.POST, Config.uploadArbeitsauftragURL, urlToFile!)

如何在我的 PHP 文件中访问该文件? 当我想使用$_FILE 时,我需要一个对应数组索引的描述符,但我无法指定。

【问题讨论】:

标签: php swift post alamofire


【解决方案1】:

我今天在制作原型时遇到了同样的问题。我的有点 hacky 的解决方案

迅速

let fileName = "myImage.png"

let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
let filePath = documentsPath.stringByAppendingPathComponent(fileName)
let fileURL = NSURL(fileURLWithPath: filePath)!

Alamofire.upload(.POST, "http://example.com/upload.php?fileName=\(fileName)", fileURL)

上传.php

// get the file data
$fileData = file_get_contents('php://input');
// sanitize filename
$fileName = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).])", '', $_GET["fileName"]);
// save to disk
file_put_contents($fileName, $fileData);

解释

Alamofire 似乎将文件作为八位字节流发送,因此只需 POST 原始文件数据。我们可以从 php://input 中获取它,但我们没有得到文件名。因此,hacky 的解决方案是在查询字符串中发送文件名。

请记住,这不是“正确”的方式。但现在可以快速解决

【讨论】:

    【解决方案2】:

    我知道,但我遇到了同样的问题。一切看起来都不错,但我无法从我的服务器应用程序访问文件数据。通过使用那里描述的方法(多部分文件上传),我能够上传文件。此外,该方法允许您上传多个文件或随请求发送其他参数。

    【讨论】:

    • 这确实提供了答案。请注意,我的第一个答案已自动转换为评论,但我无法再次发表评论,因此我需要添加新答案。但这与我的第一条评论有关。我的第一条评论指向一个解决方案,因为它谈论发送参数而被忽略,但它实际上是问题的解决方案。我知道这一点,因为我的问题与 gutenmorgenuhu 相同,我也不需要参数,但是将文件作为多部分请求上传是使上传工作的唯一方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-15
    • 2019-05-29
    • 2017-12-24
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    相关资源
    最近更新 更多