六,使用Alamofire進行文件上傳
1,Alamofire支持如下上傳類型:
File
Data
Stream
MultipartFormData
2,使用文件流的形式上傳文件
let fileURL = NSBundle.mainBundle().URLForResource("hangge", withExtension: "zip")
Alamofire.upload(.POST, "http://www.hangge.com/upload.php", file: fileURL!)
附:服務端代碼(upload.php)
<?php
/** php 接收流文件
* @param String $file 接收後保存的文件名
* @return boolean
*/
function receiveStreamFile($receiveFile){
$streamData = isset($GLOBALS['HTTP_RAW_POST_DATA'])? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
if(empty($streamData)){
$streamData = file_get_contents('php://input');
}
if($streamData!=''){
$ret = file_put_contents($receiveFile, $streamData, true);
}else{
$ret = false;
}
return $ret;
}
//定義服務器存儲路徑和文件名
$receiveFile = $_SERVER["DOCUMENT_ROOT"]."/uploadFiles/hangge.zip";
$ret = receiveStreamFile($receiveFile);
echo json_encode(array('success'=>(bool)$ret));
?>
3,上傳時附帶上傳進度
let fileURL = NSBundle.mainBundle().URLForResource("hangge", withExtension: "zip")
Alamofire.upload(.POST, "http://www.hangge.com/upload.php", file: fileURL!)
.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
print(totalBytesWritten)
// This closure is NOT called on the main queue for performance
// reasons. To update your ui, dispatch to the main queue.
dispatch_async(dispatch_get_main_queue()) {
print("Total bytes written on main queue: \(totalBytesWritten)")
}
}
.responseJSON { response in
debugPrint(response)
}
可以看到控制台不斷輸出已上傳的數據大小:
原文:Swift - HTTP網絡操作庫Alamofire使用詳解2(文件上傳)
4,上傳MultipartFormData類型的文件數據(類似於網頁上Form表單裡的文件提交)
let fileURL1 = NSBundle.mainBundle().URLForResource("hangge", withExtension: "png")
let fileURL2 = NSBundle.mainBundle().URLForResource("hangge", withExtension: "zip")
Alamofire.upload(
.POST,
"http://www.hangge.com/upload2.php",
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(fileURL: fileURL1!, name: "file1")
multipartFormData.appendBodyPart(fileURL: fileURL2!, name: "file2")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
附:服務端代碼(upload2.php)
<?
move_uploaded_file($_FILES["file1"]["tmp_name"],
$_SERVER["DOCUMENT_ROOT"]."/uploadFiles/" . $_FILES["file1"]["name"]);
move_uploaded_file($_FILES["file2"]["tmp_name"],
$_SERVER["DOCUMENT_ROOT"]."/uploadFiles/" . $_FILES["file2"]["name"]);
?>