文件下载时改变文件名

在项目中有时会出现下载文件的问题,服务器上保存的文件也许是已GUID命名的文件,但在下载时,也许需要指定一个文件名。我项目中就用到了,到这里做下笔记:
首先在页面上放一个<iframe>标签:
<iframe id="ifrLoad" frameborder="0" name="weidu" scrolling="no" width="100%" height="100%">
        </iframe>
再在js中写如下方法:
function FileDownLoad(filePath, fileName) {
    document.getElementById("ifrLoad").setAttribute("src", encodeURI("FileDownLoad.aspx?filePath=" + filePath + "&fileName=" + fileName));
}
注意文件名如果是中文要记得用:js 的encodeURI()方法进行编码传输

再到FileDownLoad.aspx页面后台代码进行转码操作,直接贴代码:

 public partial class FileDownLoad : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string filePath = Request.Params["filePath"];
            string fileName = HttpUtility.UrlDecode(Request.Params["fileName"]);
            if (filePath != null)
            {
                BigFileDownload(fileName, filePath);
            }

        }

        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="FileName">文件名</param>
        /// <param name="FilePath">路径</param>
        public void BigFileDownload(string FileName, string FilePath)
        {
            System.IO.Stream iStream = null;

            // Buffer to read 10K bytes in chunk:
            byte[] buffer = new Byte[10000];

            // Length of the file:
            int length;

            // Total bytes to read:
            long dataToRead;

            // Identify the file to download including its path.
            string filepath = System.Web.HttpContext.Current.Server.MapPath(FilePath);

            // Identify the file name.
            string filename = System.IO.Path.GetFileName(filepath);

            try
            {
                // Open the file.
                iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
                            System.IO.FileAccess.Read, System.IO.FileShare.Read);


                // Total bytes to read:
                dataToRead = iStream.Length;

                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(FileName));//System.Text.UTF8Encoding.UTF8.GetBytes(FileName)

                // Read the bytes.
                while (dataToRead > 0)
                {
                    // Verify that the client is connected.
                    if (Response.IsClientConnected)
                    {
                        // Read the data in buffer.
                        length = iStream.Read(buffer, 0, 10000);

                        // Write the data to the current output stream.
                        Response.OutputStream.Write(buffer, 0, length);

                        // Flush the data to the HTML output.
                        Response.Flush();

                        buffer = new Byte[10000];
                        dataToRead = dataToRead - length;
                    }
                    else
                    {
                        //prevent infinite loop if user disconnects
                        dataToRead = -1;
                    }
                }
            }
            catch (Exception ex)
            {
                // Trap the error, if any.
                string message = ex.Message;
                this.Page.ClientScript.RegisterStartupScript(GetType(), "Message", "<script>alert('Error : " + message + "');</script>");
            }
            finally
            {
                if (iStream != null)
                {
                    //Close the file.
                    iStream.Close();
                }
            }
        }
 }
这样当点击文件列表进行下载时:就会将以你传入的文件名作为下载的文件名
<td style=" 60%; height: 25px">
    <a href="javascript:void(0)"  onclick="FileDownLoad('../File/aseaglnsdf234dkfauoiomsadfk.doc','新设立外商投资企业区域分布情况报告(国家工商行政管理总局).doc')">新设立外商投资企业区域分布情况报告(国家工商行政管理总局)</a>
</td>

效果图如下:


实际上服务器上存的文件是:guid命名的文件
效果图如下:

作者:邹毅
如果觉得本文让你有所收获,请键点击右下角的 推荐 按钮
本文版权归作者和博客园共有,欢迎转载,但必须保留原文连接。

原文地址:https://www.cnblogs.com/joey0210/p/2163659.html