返回 导航

Swift

hangge.com

Swift - HTTP网络操作库Alamofire使用详解2(文件上传)

作者:hangge | 2015-12-08 10:03
相关文章系列:(文章代码均已升级至Swift3)
Swift - HTTP网络操作库Alamofire使用详解1(配置,以及数据请求)
[当前文章] Swift - HTTP网络操作库Alamofire使用详解2(文件上传)
Swift - HTTP网络操作库Alamofire使用详解3(文件下载,断点续传)
Swift - HTTP网络操作库Alamofire使用详解4(用户权限认证)


六,使用Alamofire进行文件上传

1,Alamofire支持如下上传类型:
File
Data
Stream
MultipartFormData

2,使用文件流的形式上传文件
let fileURL = Bundle.main.url(forResource: "hangge", withExtension: "zip")

Alamofire.upload(fileURL!, to: "http://www.hangge.com/upload.php")
    .responseJSON { response in
        debugPrint(response)
    }
  附:服务端代码(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));  
?>
如何在上传时附带上文件名?
有时我们在文件上传的同时还会想要附带一些其它参数,比如文件名。这样服务端接收到文件后,就可以根据我们传过来的文件名来保存。实现这个其实很简单,客户端和服务端分别做如下修改。
  • 客户端:将文件名以参数的形式跟在链接后面。比如:http://hangge.com/upload.php?fileName=image1.png
  • 服务端:通过 $_GET["fileName"] 得到这个参数,并用其作为文件名保存。

3,上传时附带上传进度
let fileURL = Bundle.main.url(forResource: "hangge", withExtension: "zip")

Alamofire.upload(fileURL!, to: "http://www.hangge.com/upload.php")
    .uploadProgress { progress in // main queue by default
        print("当前进度: \(progress.fractionCompleted)")
    }
    .responseJSON { response in
        debugPrint(response)
    }
可以看到控制台不断输出已上传的进度(1则表示上传完毕): 

4,上传MultipartFormData类型的文件数据(类似于网页上Form表单里的文件提交)
(1)上传两个文件
let fileURL1 = Bundle.main.url(forResource: "hangge", withExtension: "png")
let fileURL2 = Bundle.main.url(forResource: "hangge", withExtension: "zip")

Alamofire.upload(
    multipartFormData: { multipartFormData in
        multipartFormData.append(fileURL1!, withName: "file1")
        multipartFormData.append(fileURL2!, withName: "file2")
    },
    to: "http://www.hangge.com/upload2.php",
    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"]);
?>

(2)文本参数与文件一起提交(文件除了可以使用fileURL,还可以上传NSData类型的文件数据)
//字符串
let strData = "hangge.com".data(using: String.Encoding.utf8)
//数字
let intData = String(10).data(using: String.Encoding.utf8)
//文件1
let path = Bundle.main.url(forResource: "hangge", withExtension: "png")!
let file1Data = try! Data(contentsOf: path)
//文件2
let file2URL = Bundle.main.url(forResource: "hangge", withExtension: "zip")

Alamofire.upload(
    multipartFormData: { multipartFormData in
        multipartFormData.append(strData!, withName: "value1")
        multipartFormData.append(intData!, withName: "value2")
        multipartFormData.append(file1Data, withName: "file1",
                                 fileName: "h.png", mimeType: "image/png")
        multipartFormData.append(file2URL!, withName: "file2")
    },
    to: "http://www.hangge.com/upload2.php",
    encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                debugPrint(response)
            }
        case .failure(let encodingError):
            print(encodingError)
        }
    }
)
  附:服务端代码(upload2.php)
<? 
$value1 = $_POST["value1"];
$value2 = $_POST["value2"];

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"]);
?>
评论

全部评论(7)

回到顶部