PHPサーバーに、画像とテキストを同時にアップロードする
URLRequest with multipart support · GitHub
↑ このサイトの URLRequest+Multipart.swift を使う。
ViewController.swift
override func viewDidLoad() { super.viewDidLoad() let url = NSURL(string: "https://【ドメイン】/upload.php")! let imageJpgData = image.jpegData(compressionQuality: 1.0)! let imagePngData = image.pngData()! let request = URLRequest(multipartFormData: { (formData) in //1. Example with URL to local file // try? formData.append(fileUrl: URL(string: "path to file")!, name: "parameterKey") //2. Example with Data of a file formData.append(file: imageJpgData, name: "upload_img_jpg", fileName: "test01.jpg", mimeType: "image/jpeg") formData.append(file: imagePngData, name: "upload_img_png", fileName: "test01.png", mimeType: "image/png") //3. Example of key/value pair formData.append(value: "upload_txt_test", name: "upload_txt") }, url: url as URL, method: .post, headers: [:]) let task = URLSession.shared.dataTask(with: request) { data, response, error in if error != nil { print("error=\(String(describing: error))") return } task.resume() }
PHPサーバー
<?php if(isset($_FILES)&& isset($_FILES['upload_img_png']) && is_uploaded_file($_FILES['upload_img_png']['tmp_name'])){ if(!file_exists('upload')){ mkdir('upload'); } $a = 'upload/' . basename($_FILES['upload_img_png']['name']); if(move_uploaded_file($_FILES['upload_img_png']['tmp_name'], $a)){ $msg = $a. 'のアップロードに成功しました'; }else { $msg = 'アップロードに失敗しました'; } } if(isset($_FILES)&& isset($_FILES['upload_img_jpg']) && is_uploaded_file($_FILES['upload_img_jpg']['tmp_name'])){ if(!file_exists('upload')){ mkdir('upload'); } $a = 'upload/' . basename($_FILES['upload_img_jpg']['name']); if(move_uploaded_file($_FILES['upload_img_jpg']['tmp_name'], $a)){ $msg = $a. 'のアップロードに成功しました'; }else { $msg = 'アップロードに失敗しました'; } } file_put_contents($_POST["upload_txt"].'.txt',$_POST["upload_txt"]); echo "finish!!"; ?>