======例,在某列中找出下載的檔案資料===============
protected void DownloadDoc_Click(object sender, EventArgs e) {
ImageButton imageButton = (ImageButton)sender;
TableCell tableCell = (TableCell)imageButton.Parent;
GridViewRow row = (GridViewRow)tableCell.Parent;
;
//GridView1.SelectedIndex = row.RowIndex;
//doc path is found by the datakey attribute of grid and corresponding field/column
string docPath = GridView1.DataKeys[row.RowIndex]["DOC_PATH"].ToString();
//trigger the download process.
string filename = Path.GetFileName(docPath);
System.IO.Stream stream = null;
try
{
// Open the file into a stream.
stream = new FileStream(docPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
// Total bytes to read:
long bytesToRead = stream.Length;
Response.ContentType = "application/octet-stream";
string fileExt = Path.GetExtension(docPath);
Response.AddHeader("Content-Disposition", "attachment; filename=" +
util.MisFunc.ConvertDateTimeToJavaMilliSecond(System.DateTime.Now) + fileExt);
// Read the bytes from the stream in small portions.
while (bytesToRead > 0)
{
// Make sure the client is still connected.
if (Response.IsClientConnected)
{
// Read the data into the buffer and write into the
// output stream.
byte[] buffer = new Byte[10000];
int length = stream.Read(buffer, 0, 10000);
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
// We have already read some bytes.. need to read
// only the remaining.
bytesToRead = bytesToRead - length;
}
else
{
// Get out of the loop, if user is not connected anymore..
bytesToRead = -1;
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
// An error occurred..
}
finally
{
if (stream != null)
{
stream.Close();
}
}
}
====================================================
那ASP.net MVC4呢?
==============MVC4的寫法更簡潔======================
using System.Net.Mime;
using System.IO;
...
...
public FileStreamResult getPdfFile(string path) {string path = (string)recFile["DOC_PATH"];
var contentDisposition = new ContentDisposition
{
FileName = "doc.pdf",
Inline = true
};
Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
byte[] bytes = System.IO.File.ReadAllBytes(path); //ReportStore.GetProfileInByte(path);
MemoryStream ms = new MemoryStream(bytes);
return new FileStreamResult(ms, MediaTypeNames.Application.Pdf);
}
================================================