自动从第三方下载资源到本地

有个同事从别人服务器捞了一份源代码下来,这个网站的主要是一些图片和flash动画资源文件,值钱的东西也是这些,权限控制啥的基本形同虚设。

但是图片和动画文件太多,没办法一个一个去网页上看地址一个一个下载,所以呢我们就需要把别人服务器文件按照目录结构自动下载到我们自己的服务器。

这里.net里面只需要截取请求地址,解析地址中相对路径,自动从第三方下载到本地对应路径就行了。

这里列出一个HttpModule的范例。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;

namespace HttpDownload
{
    public class DownloadModule : IHttpModule
    {
        public void Dispose()
        {
            throw new NotImplementedException();
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        /// <summary>
        /// Request监听事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication httpApp = (HttpApplication)sender;
            // 获取请求的完整的地址
            var url = httpApp.Request.RawUrl;
            // 正则表达式截取{.字母结尾}的请求
            // 此处只是简单的地址判断,可以根据自己的要求修改这部分的正则表达式
            var regex = new Regex("[^/]*[.]{1}[a-zA-Z]*$");
            // 判断是否满足条件
            if (regex.IsMatch(url))
            {
                // 获取相对路径地址
                string path = httpApp.Request.Url.AbsolutePath;
                // 开始下载文件
                DownloadFile("www.domain.com", path);
            }

        }

        /// <summary>
        /// 从服务器下载文件
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="absolutePath"></param>
        void DownloadFile(string domain, string absolutePath)
        {
            // 按照相对路径获取本地文件路径
            string localPath = HttpContext.Current.Server.MapPath(absolutePath);
            // 判断文件是否存在,已经存在的文件不重复下载
            if (!File.Exists(localPath))
            {
                // 文件夹不存在自动创建文件夹
                string directory = Path.GetDirectoryName(localPath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                // 相对路径拼接第三方文件的地址,下载文件
                var request = HttpWebRequest.Create($"http://{domain}{absolutePath}");
                var response = request.GetResponse();
                int bytesProcessed = 0;
                Stream stream = response.GetResponseStream();
                FileStream fs = File.Create(localPath);

                byte[] buffer = new byte[1024];
                int bytesRead;

                do
                {
                    bytesRead = stream.Read(buffer, 0, buffer.Length);
                    fs.Write(buffer, 0, bytesRead);
                    bytesProcessed += bytesRead;
                } while (bytesRead > 0);



                fs.Flush();
                fs.Close();
                response.Close();

            }
        }
    }
}

修改Web.config,添加HttpModule

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <!-- IIS7.0经典模式或者IIS之前版本 -->
    <!--<httpModules>
      <add name="downloadModule" type="HttpDownload.DownloadModule,HttpDownload"/>
    </httpModules>-->
  </system.web>
  <!-- IIS7.0集成模式下 -->
  <system.webServer>
    <modules>
      <add name="downloadModule" type="HttpDownload.DownloadModule,HttpDownload"/>
    </modules>
  </system.webServer>
</configuration>

这里的Web.config在不同版本的IIS版本模式下配置可能会有不同,配置的时候注意自己的环境。

原文地址:https://www.cnblogs.com/stealth7/p/8418705.html