Vi. use Alamofire for file upload
1,alamofire supports the following types of uploads:
File
Data
Stream
Multipartformdata
2, upload files using the file stream
Let FileURL = Nsbundle.mainbundle (). Urlforresource ("Hangge", Withextension: "Zip")
Alamofire.upload (. POST, "http://www.hangge.com/upload.php", file:fileurl!)
Attached: Service-side code (upload.php)
<?php
/** PHP Receive stream files
* @param String $file The file name saved after receiving
* @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;
}
Define server storage path and filename
$receiveFile = $_server["Document_root"]. " /uploadfiles/hangge.zip ";
$ret = Receivestreamfile ($receiveFile);
Echo json_encode (' Success ' => (BOOL) $ret));
?>
3, upload with upload progress
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 isn't called on the main \ 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)
}
You can see that the console is constantly outputting the uploaded data size:
Original: Swift-http network operation library Alamofire use detailed 2 (file upload)
4, upload the Multipartformdata type of file data (similar to the file submitted in the form form on the Web page)
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)
}
}
)
Attached: Service-side code (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"]);
?>