获取下载文件的路径

//下载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

时间: 2024-10-12 04:16:22

获取下载文件的路径的相关文章

VC 获取指定文件夹路径的方法小结

VC获取指定文件夹路径 flyfish  2010-3-5 一 使用Shell函数 1 获取应用程序的安装路径 TCHAR buf[_MAX_PATH];SHGetSpecialFolderPath(NULL,buf,CSIDL_PROGRAM_FILES,NULL);AfxMessageBox(buf); 2 获取应用程序数据路径的文件夹 TCHAR bufApplicateData[_MAX_PATH];SHGetSpecialFolderPath(NULL,bufApplicateData

python 获取当前文件夹路径及父级目录的几种方法

获取当前文件夹路径及父级目录: import os current_dir = os.path.abspath(os.path.dirname(__file__)) print(current_dir) #F:\project\pritice current_dir1 = os.path.dirname(__file__) print(current_dir1) #F:/project/pritice parent_path = os.path.dirname(current_dir1) pri

(判断url文件大小)关于inputStream.available()方法获取下载文件的总大小

转自:http://hold-on.iteye.com/blog/1017449 Java代码   如果用inputStream对象的available()方法获取流中可读取的数据大小,通常我们调用这个函数是在下载文件或者对文件进行其他处理时获取文件的总大小. 以前在我们初学File和inputStream和outputStream时,有需要将文件从一个文件夹复制到另一个文件夹中,这时候我们用的就是inputStream.available()来获取文件的总大小,而且屡试不爽. 但是当我们要从网

获取下载文件的大小

在使用PowerShell下载文件时,总希望展示一个进度条来查看下载进程 这就需要知道下载文件的大小,然后通过百分比的形式显示进度 要获得下载文件的大小可以使用如下: function Get-DownloadSize { [CmdletBinding()] Param ( [Parameter(Mandatory,ValueFromPipeline)] [String] $url ) Process { $webRequest=[System.Net.WebRequest]::Create($

firemonkey获取当前文件所在路径的方法

在之前,我们知道有三种方法: ExtractFilePath(ParamStr(0)) ExtractFilePath(Application.ExeName) GetCurrentDir + '\' 在firemonkey中,Windows模式下第一种.第三种还有效: ExtractFilePath(ParamStr(0)) GetCurrentDir + '\' iOS模式下,是用:GetHomePath来获得APP的安装路径.

[SoapUI] 比较TP和Live环境下的XML Response,将代码按照功能进行拆分,根据代码所在目录自动获取Mapping文件所在路径,自动获取测试步骤名称

import org.custommonkey.xmlunit.* import org.custommonkey.xmlunit.examples.* import javax.xml.xpath.* import javax.xml.parsers.* import static java.lang.Math.* import com.eviware.soapui.support.GroovyUtils // The parameter allowableDeviation means th

获取 ProgramData 文件夹路径

char startUpDir[500]; if (SHGetFolderPathA( NULL, CSIDL_COMMON_STARTUP, NULL, 0, startUpDir) != S_OK) { printf("SHGetFolderPathA failed."); } 原文地址:https://www.cnblogs.com/liujx2019/p/10634862.html

通过路径下载文件

function getFile($url, $save_dir = '', $filename = '', $type = 0) { if (trim($url) == '') { return false; } if (trim($save_dir) == '') { $save_dir = './'; } if (0 !== strrpos($save_dir, '/')) { $save_dir.= '/'; } //创建保存目录 if (!file_exists($save_dir)

python获取Windows特殊文件夹路径

有时候你想给你的程序添加桌面快捷方式,但却连桌面的准确路径都不知道,还好微软的API给出了一些特殊文件夹路径的获取方法,再利用python的win32com模块(非标准库)即可在python中实现同样的操作! # -*- coding: cp936 -*- from win32com.shell import shell from win32com.shell import shellcon #获取"启动"文件夹路径,关键是最后的参数CSIDL_STARTUP,这些参数可以在微软的官方