Here is my swift code that uploads the file from application.
final class UploadService {
// I'm renting a remote server and the php code is on that
private let videoUploadPath = "http://myUploadPath.php"
var uploadsSession: URLSession!
var activeUploads: [URL: Upload] = [:]
func startUpload(medium: Medium) {
guard let url = URL(string: videoUploadPath) else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
let upload = Upload(medium: medium)
upload.task = self.uploadsSession.uploadTask(with: request, fromFile: medium.avUrlAsset.url)
upload.task?.resume()
upload.isUploading = true
activeUploads[upload.medium.avUrlAsset.url] = upload
}
}
Note that I have to use
func uploadTask(with request: URLRequest, fromFile fileURL: URL) -> URLSessionUploadTask
// Apple documentation:
Parameters
request
A URL request object that provides the URL, cache policy, request type,
and so on. The body stream and body data in this request object are ignored.
to upload video from phone, since that's the only method that allows background upload (videos are normally pretty big, therefore I HAVE TO make background upload possible). However, this function discard all body data.
Here is the my PHP code that receives the uploaded file and stores it in the desired location:
$directory = "../storage/videos/";
$destination = $directory . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $destination)) {
$returnArray["status"] = "200";
$returnArray["message"] = "Upload success";
echo json_encode($returnArray);
} else {
$returnArray["status"] = "300";
$returnArray["message"] = "Upload failed" . $_FILES["file"]["error"];
echo json_encode($returnArray);
return;
}
To be honest, I know it won't succeed, because I have no way to specify the file type and name, which are required by $_FILES["file"]["name"]
in the PHP code.
Therefore, my question is, how to specify file name and type to be uploaded? Since the function
func uploadTask(with request: URLRequest, fromFile fileURL: URL) -> URLSessionUploadTask
discards all http body data, as I mentioned, perhaps making an http header that contains the file type and name? OR, is there another way for PHP to receive the file I just uploaded? For now, the $_FIELS is completely empty. I'm new to PHP, sorry if I didn't say it clearly enough.
Also, for Content-Type
, I was using multipart/form-data
when I upload an image to change user's profile image, I append the image data together with other data like uid
, then attach those data as the body data in the http body. But now, I need to upload a single file, because all body data in the request will be ignored per iOS requirement. How can I do this?
Many days stuck in this, please help. Many thanks!!