一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Swift HTTP网络操作库Alamofire实现文件上传详解

时间:2022-06-25 23:42:28 编辑:袖梨 来源:一聚教程网

六,使用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 接收流文件
* @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"]);
?>

热门栏目