0

I use the .upload method to upload to a php file on my server and it seems to work (I get a 200 response)

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

How can I access this file in my PHP file ? When I want to use $_FILE, I would need a descriptor for the corresponding array-index and I am not able to specify any.

gutenmorgenuhu
  • 2,312
  • 1
  • 19
  • 33

2 Answers2

2

I came across this same problem today while prototyping something. My slightly hacky solution

swift

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)

upload.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);

explanation

It seems Alamofire is sending the file as a octet-stream, so just POSTing the raw file data. We can grab this from php://input but we don't get a filename. So the hacky solution is to just send the filename in the query string.

Remember, this isn't the "right" way. But it's a quick fix for now

RShergold
  • 36
  • 1
  • 6
0

I know, but I had the same problem. Everything looked ok but I couldn't access the file data from my server app. By using the method described there (multipart file upload) I was able to upload the file. Additionally, that method allows you to upload more than one file or send other parameters with the request.

ncerezo
  • 1,331
  • 12
  • 11
  • This does provide an answer. Please, note that my first answer was converted automatically to a comment, but I could no comment again, so I needed to add a new answer. But this is connected to my first comment. My first comment points to a solution, disregarded because it talks about sending parameters, but it is actually the solution to the problem. I know it because my problem was the same gutenmorgenuhu has, I didn't need parameters either, but uploading the file as a multipart request was the only way to make the upload work. – ncerezo Jun 05 '15 at 07:23