前段時間一直在wordpress的在線更新是如果實現的。分析了一下,大致邏輯應該是先遠程下載網絡打包文件,然后解壓執行替換。那么如何實現下載遠程網絡文件呢?今天無意間找到這段代碼:
php源代碼:
<form method=”post”>
<input name=”url” size=”50″ />
<input name=”submit” type=”submit” />
</form>
< ?php
// maximum execution time in seconds
set_time_limit (24 * 60 * 60);
if (!isset($_POST['submit'])) die();
// folder to save downloaded files to. must end with slash
$destination_folder = 'temp/';
$url = $_POST['url'];
$newfname = $destination_folder . basename($url);
$file = fopen ($url, "rb");
if ($file) {
$newf = fopen ($newfname, "wb");
if ($newf)
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
?>
ASP源代碼:
< %
function downfilea(d_target, s_target)
On Error Resume Next
dim myhttp, objstream
set myhttp = server.createobject( "MSXML2.XMLHTTP ")
myhttp.open "GET ", d_target, false
myhttp.send()
set objstream = Server.CreateObject( "adodb.stream ")
objstream.Type = 1
objstream.Mode = 3
objstream.Open
objstream.Write myhttp.responseBody
objstream.SaveToFile s_target, 2
if err.number <> 0 then err.Clear
end function
downfilea “http://www.abc.com/xxx.rar “, Server.MapPath( “down/xxx.rar “)
Response.write “ok ”
%>
還有asp.net版本的源碼(未測試)
using System;
using System.Net;
using System.IO;
class DownloadFile;
{
static void Main(string[] args)
{
//你的遠程文件
string siteURL=”http://www.abc.com/xxx.rar”;
//下載到本地的路徑及文件名
string fileName=”c:\\xxx.rar”;
//實例化一個WebClient
WebClient client=new WebClient();
//調用WebClient的DownloadFile方法
client.DownloadFile(siteURL,fileName);
}
}
注意事項:
1.相關的目錄可能需要建立.
2.其中php版本的源碼是支持自定義url的,但asp、asp.net版本的並沒有提供自定義.
3.在拷貝大文件時,國內估計支持欠佳.因為考慮到程序的超時時間,但在國外支持很好.
比如將一個近300M的文件轉移到另一個服務器上耗費時間是28秒.這是國內無法想象的.