다음은 대상 업로드 URL, 매개 변수 및 imageData를 요구하고 Alamofire.upload가 매개 변수와 함께 이미지를 업로드하는 데 필요한 URLRequestConvertible 및 NSData를 반환하는 간단한 함수입니다.
// this function creates the required URLRequestConvertible and NSData we need to use Alamofire.upload
func urlRequestWithComponents(urlString:String, parameters:Dictionary<String, String>, imageData:NSData) -> (URLRequestConvertible, NSData) {
// create url request to send
var mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue
let boundaryConstant = "myRandomBoundary12345";
let contentType = "multipart/form-data;boundary="+boundaryConstant
mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
// create upload data to send
let uploadData = NSMutableData()
// add image
uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData("Content-Disposition: form-data; name=\"file\"; filename=\"file.png\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData(imageData)
// add parameters
for (key, value) in parameters {
uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
}
uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
// return URLRequestConvertible and NSData
return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)
}
다음은 사용 방법의 예입니다 (요청 생성 및 보내기 참조).
// init paramters Dictionary
var parameters = [
"task": "task",
"variable1": "var"
]
// add addtionial parameters
parameters["userId"] = "27"
parameters["body"] = "This is the body text."
// example image data
let image = UIImage(named: "177143.jpg")
let imageData = UIImagePNGRepresentation(image)
// CREATE AND SEND REQUEST ----------
let urlRequest = urlRequestWithComponents("http://example.com/uploadText/", parameters: parameters, imageData: imageData)
Alamofire.upload(urlRequest.0, urlRequest.1)
.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
println("\(totalBytesWritten) / \(totalBytesExpectedToWrite)")
}
.responseJSON { (request, response, JSON, error) in
println("REQUEST \(request)")
println("RESPONSE \(response)")
println("JSON \(JSON)")
println("ERROR \(error)")
}
그리고 대상 URL에 대한 php 파일이 필요한 경우 (동일한 디렉토리에 'uploads'폴더 포함) :
// get picture variables
$file = $_FILES['file']['tmp_name'];
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
// check extension
$allowedExts = array("jpg", "jpeg", "png");
$rootName = reset(explode(".", $fileName));
$extension = end(explode(".", $fileName));
// create new file name
$time = time();
$newName = $rootName.$time.'.'.$extension;
// temporarily save file
$moved = move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/".$newName );
if ($moved) $path = "uploads/".$newName;
$body = $_POST['body'];
$userId = $_POST['userId'];
$time = time();
if ($moved) {
$fullUrl = "http://antiblank.com/testPhotoUpload/".$path;
$arrayToSend = array('status'=>'success','time'=>$time,'body'=>$body,'userId'=>$userId, "imageURL"=>$fullUrl);
} else {
$arrayToSend = array('status'=>'FAILED','time'=>$time,'body'=>$body,'userId'=>$userId);
}
header('Content-Type:application/json');
echo json_encode($arrayToSend);