檔案下載下傳類:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace pxcom
{
/// <summary>
///
/// </summary>
public class FileResult : ActionResult
{
private readonly string _filePath;//檔案路徑
private readonly string _fileName;//檔案名稱
public FileResult(string filePath, string fileName)
{
_filePath = filePath;
_fileName = fileName;
}
public override void ExecuteResult(ControllerContext context)
{
string fileName = _fileName;
HttpResponseBase response = context.HttpContext.Response;
if (File.Exists(_filePath))
{
FileStream fs = null;
byte[] fileBuffer = new byte[1024];//每次讀取1024位元組大小的資料
try
{
using (fs = File.OpenRead(_filePath))
{
long totalLength = fs.Length;
response.ContentType = "application/octet-stream";
response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
while (totalLength > 0 && response.IsClientConnected)//持續傳輸檔案
{
int length = fs.Read(fileBuffer, 0, fileBuffer.Length);//每次讀取1024個位元組長度的内容
fs.Flush();
response.OutputStream.Write(fileBuffer, 0, length);//寫入到響應的輸出流
response.Flush();//重新整理響應
totalLength = totalLength - length;
}
response.Close();//檔案傳輸完畢,關閉相應流
}
}
catch (Exception ex)
{
response.Write(ex.Message);
}
finally
{
if (fs != null)
fs.Close();//最後記得關閉檔案流
控制器:
public ActionResult GetFile(string url)
{
string path = pxcom.Util.GetKejianPath() + url;
var filename = Path.GetFileName(path);
return new
public static void Down(string url,string saveFileName)
{
string svr = System.Configuration.ConfigurationManager.AppSettings["svraddress"];
url = svr + "/" + url;
new