1. 程式人生 > >獲取下載文件的路徑

獲取下載文件的路徑

amp lencod 文件夾的名稱 文件的 sys post start 文件路徑 exce

//下載action

public void GetFile(string guid)
{
if (string.IsNullOrEmpty(guid))
{
Response.Write("<script>alert(‘參數錯誤‘);</script>");
}

//獲取下載文件路徑
string filePath = GetDownPath(guid);
if (!System.IO.File.Exists(filePath))
{
Response.Write("<script>alert(‘文件不存在‘);</script>");
return;
}

ChunkTransfer(System.Web.HttpContext.Current, filePath);
HttpContext.Response.Flush();

string tempFolder = fileName.Substring(0, fileName.LastIndexOf(‘\\‘));
//刪除臨時文件
DeleteDirectory(tempFolder);
}

//guid為創建下載文件時,所保存在的文件夾的名稱,且該文件夾下只有一個文件,為要下載的文件

public string GetDownPath(string guid)
{

string fileDirectory = Path.Combine("臨時文件夾", "文件路徑");
if (Directory.Exists(fileDirectory))
{
DirectoryInfo dirInfo = new DirectoryInfo(fileDirectory);
string fileName = string.Empty;

//然後在當前路徑下查找excel文件
FileInfo[] fileInfo = dirInfo.GetFiles("*.xlsx");
if (fileInfo != null && fileInfo.Count() > 0)
{
foreach (FileInfo file in dirInfo.GetFiles("*.xlsx"))
{
fileName = file.FullName.Substring(file.FullName.LastIndexOf("\\") + 1);
}
}
return Path.Combine(fileDirectory, fileName);
}
return "";
}

//將文件放到輸出流中

public bool ChunkTransfer(HttpContext httpContext, string filePathName)
{
bool result = false;

if (!System.IO.File.Exists(filePathName))
{
httpContext.Response.StatusCode = 404;
return false;
}
long startPostion = 0;
long endPostion = 0;
string fileName = Path.GetFileName(filePathName);
using (FileStream fileStream = new FileStream(filePathName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (BinaryReader br = new BinaryReader(fileStream))
{
long fileLength = fileStream.Length;
string lastUpdateTime = System.IO.File.GetLastWriteTimeUtc(filePathName).ToString("r");
string eTag = HttpUtility.UrlEncode(fileName, Encoding.UTF8) + lastUpdateTime;//恢復下載時提取請求頭;
if (httpContext.Request.Headers["If-Range"] != null)
{
if (httpContext.Request.Headers["If-Range"].Replace("\"", "") != eTag)
{//文件修改過
httpContext.Response.StatusCode = 412;//預處理失敗
return false;
}
}

httpContext.Response.Clear();
httpContext.Response.Buffer = false;
httpContext.Response.AddHeader("Accept-Ranges", "bytes");
httpContext.Response.AppendHeader("ETag", "\"" + eTag + "\"");
httpContext.Response.AppendHeader("Last-Modified", lastUpdateTime);//把最後修改日期寫入響應
httpContext.Response.ContentType = "application/octet-stream";
if (httpContext.Request.UserAgent.IndexOf("MSIE") > -1 || (httpContext.Request.UserAgent.IndexOf("like Gecko") > -1))
{
fileName = HttpUtility.UrlEncode(fileName, Encoding.UTF8).Replace("+", "%20");
}

if (httpContext.Request.UserAgent.ToLower().IndexOf("firefox") > -1)
{
httpContext.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
}
else
{
httpContext.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
}
httpContext.Response.AddHeader("Connection", "Keep-Alive");
httpContext.Response.ContentEncoding = Encoding.UTF8;
if (httpContext.Request.Headers["Range"] != null)//續傳
{
httpContext.Response.StatusCode = 206;//續傳標識
string[] range = httpContext.Request.Headers["Range"].Split(new char[] { ‘=‘, ‘-‘ });
startPostion = long.Parse(range[1]);//已經下載的字節數
if (startPostion < 0 || startPostion >= fileLength)
{
return false;
}
if (string.IsNullOrEmpty(range[2]))//只指定請求文件起始
{
httpContext.Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startPostion, fileLength - 1, fileLength));
httpContext.Response.AddHeader("Content-Length", (fileLength - startPostion).ToString());
}
else//指定請求文件範圍
{
endPostion = long.Parse(range[2]);
httpContext.Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startPostion, endPostion - startPostion - 1, fileLength));
httpContext.Response.AddHeader("Content-Length", (endPostion - startPostion).ToString());
}
}
else
{//非續傳
httpContext.Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startPostion, fileLength - 1, fileLength));
httpContext.Response.AddHeader("Content-Length", (fileLength - startPostion).ToString());
}

br.BaseStream.Seek(startPostion, SeekOrigin.Begin);
long maxCount = (long)Math.Ceiling((fileLength - startPostion + 0.0) / TransferBuffer);//分塊下載,剩余部分可分成的塊數
for (long i = 0; i < maxCount && httpContext.Response.IsClientConnected; i++)
{
httpContext.Response.BinaryWrite(br.ReadBytes(TransferBuffer));
httpContext.Response.Flush();
if (TransferSleep > 0)
{
Thread.Sleep(TransferSleep);
}
}

result = true;

}
}


return result;
}

#region 刪除文件夾
/// <summary>
/// 如指定目錄存在,刪除其並刪除該目錄中的任何子目錄
/// </summary>
/// <param name="path">目錄路徑</param>
public static void DeleteDirectory(string path)
{
if (string.IsNullOrEmpty(path.Trim()))
return;
if (Directory.Exists(path))
{
Directory.Delete(path, true);
}
}

#endregion

獲取下載文件的路徑