0

我想让一些用户从我的网站下载一些文件,我不希望他们看到下载文件的物理路径。

我将文件移动到我的 web 文件夹之外的文件夹中,并使用 Response.WriteFile(filePath) 下载它们。这有助于我隐藏路径,但这种方法不支持我真正想要的恢复下载。

那你推荐我用什么方法?

4

4 回答 4

1

创建一个临时目录并将文件复制到那里。您甚至可以将文件重命名为其他名称,使其不可“猜测”。

我假设他们是否可以下载该文件,其内容适用于该人,因此用户知道直接链接是没有问题的。其他人将无法猜测随机目录和/或文件名。

var directoryName = String.Format("{0}\{1}\{2}", 
Server.MapPath("original Path"),System.Guid.NewGuid().Replace("-",""), fileName);

这与我们用于从系统导出信息的过程几乎相同。

于 2013-02-08T08:46:20.277 回答
0

很简单,我以前也做过。只需隐藏“输入文件”控件,使其隐藏在 UI 上,然后创建一个单击事件触发“输入文件”控件的单击事件的按钮。然后,您还可以使用 javascript(在我的情况下是 JQuery),将浏览文件的名称放入代表文件名称的文本框中。

因此,文件路径对 UI 是隐藏的。

于 2013-02-08T08:47:44.297 回答
0

我将实现一个文件处理程序(.ashx 文件),它根据查询字符串中的某种 id 或名称来提供文件,并像这样发送它:

asp.net ashx 处理程序提示下载而不是显示文件

于 2013-02-08T08:56:40.907 回答
0

这是最好的方法:

    public static bool DownloadFile(HttpContext httpContext, string filePath, long speed)
    {
        // Many changes: mostly declare variables near use
        // Extracted duplicate references to HttpContext.Response and .Request
        // also duplicate reference to .HttpMethod

        // Removed try/catch blocks which hid any problems
        var response = httpContext.Response;
        var request = httpContext.Request;
        var method = request.HttpMethod.ToUpper();
        if (method != "GET" &&
            method != "HEAD")
        {
            response.StatusCode = 501;
            return false;
        }

        if (!File.Exists(filePath))
        {
            response.StatusCode = 404;
            return false;
        }

        // Stream implements IDisposable so should be in a using block
        using (var myFile = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            var fileLength = myFile.Length;
            if (fileLength > Int32.MaxValue)
            {
                response.StatusCode = 413;
                return false;
            }

            var lastUpdateTiemStr = File.GetLastWriteTimeUtc(filePath).ToString("r");
            var fileName = Path.GetFileName(filePath);
            var fileNameUrlEncoded = HttpUtility.UrlEncode(fileName, Encoding.UTF8);
            var eTag = fileNameUrlEncoded + lastUpdateTiemStr;

            var ifRange = request.Headers["If-Range"];
            if (ifRange != null && ifRange.Replace("\"", "") != eTag)
            {
                response.StatusCode = 412;
                return false;
            }

            long startBytes = 0;

            // Just guessing, but I bet you want startBytes calculated before
            // using to calculate content-length
            var rangeHeader = request.Headers["Range"];
            if (rangeHeader != null)
            {
                response.StatusCode = 206;
                var range = rangeHeader.Split(new[] { '=', '-' });
                startBytes = Convert.ToInt64(range[1]);
                if (startBytes < 0 || startBytes >= fileLength)
                {
                    // TODO: Find correct status code
                    response.StatusCode = (int)HttpStatusCode.BadRequest;
                    response.StatusDescription =
                        string.Format("Invalid start of range: {0}", startBytes);
                    return false;
                }
            }

            response.Clear();
            response.Buffer = false;
            response.AddHeader("Content-MD5", GetMD5Hash(filePath));
            response.AddHeader("Accept-Ranges", "bytes");
            response.AppendHeader("ETag", string.Format("\"{0}\"", eTag));
            response.AppendHeader("Last-Modified", lastUpdateTiemStr);
            response.ContentType = "application/octet-stream";
            response.AddHeader("Content-Disposition", "attachment;filename=" +
                                                        fileNameUrlEncoded.Replace("+", "%20").Replace(",",";"));
            var remaining = fileLength - startBytes;
            response.AddHeader("Content-Length", remaining.ToString());
            response.AddHeader("Connection", "Keep-Alive");
            response.ContentEncoding = Encoding.UTF8;

            if (startBytes > 0)
            {
                response.AddHeader("Content-Range",
                                    string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
            }

            // BinaryReader implements IDisposable so should be in a using block
            using (var br = new BinaryReader(myFile))
            {
                br.BaseStream.Seek(startBytes, SeekOrigin.Begin);

                const int packSize = 1024 * 10; //read in block,every block 10K bytes
                var maxCount = (int)Math.Ceiling((remaining + 0.0) / packSize); //download in block
                for (var i = 0; i < maxCount && response.IsClientConnected; i++)
                {
                    response.BinaryWrite(br.ReadBytes(packSize));
                    response.Flush();

                    // HACK: Unexplained sleep
                    var sleep = (int)Math.Ceiling(1000.0 * packSize / speed); //the number of millisecond
                    if (sleep > 1) 
                        Thread.Sleep(sleep);
                }
            }
        }
        return true;
    }

    static string GetMD5Hash(string input)
    {
        // Create a new instance of the MD5CryptoServiceProvider object.
        MD5 md5Hasher = MD5.Create();

        // Convert the input string to a byte array and compute the hash.
        byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

        // Create a new Stringbuilder to collect the bytes
        // and create a string.
        StringBuilder sBuilder = new StringBuilder();

        // Loop through each byte of the hashed data 
        // and format each one as a hexadecimal string.
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }

        // Return the hexadecimal string.
        return sBuilder.ToString();
    }
于 2013-02-15T07:36:12.127 回答