已下载的文件已破坏其格式 [英] Downloaded file has broken its format
问题描述
我为我的网络应用程序编写了一个代码,我正在上传一些文件(Pdf和png等)并在gridview中显示这些文件。我希望在点击行时从gridview下载上传的文件。我已成功完成该任务,但是当我打开下载的文件时,我面临文件无法打开的错误。我怎么摆脱它。
这是我用来从gridview下载文件的代码。
我尝试过:
protected void GridView1_RowCommand(object sender,GridViewCommandEventArgs e)
{
if(e.CommandName ==Download){
Response.Clear();
Response.ContentType =application / octect-stream;
Response.AppendHeader(content-disposition,filename =+ e.CommandArgument);
Response.End();
}
}
I have written a code for my web application, i which i am uploading some files (Pdf and png etc) and displaying the files in the gridview. I am desirous to download the uploaded file from gridview on clicking the row. I have successfully done that task, but when i open the downloaded file, i face the error that "File is unable to open". How i can get rid from that.
Here is my code which i am using to download the file from the gridview.
What I have tried:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Download") {
Response.Clear();
Response.ContentType = "application/octect-stream";
Response.AppendHeader("content-disposition","filename="+ e.CommandArgument);
Response.End();
}
}
推荐答案
你需要做类似下面的代码
you need to do like below code
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
byte[] bytes = br.ReadBytes((Int32)fs.Length);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
代码未经测试需要检查
code is not tested you need to check
这篇关于已下载的文件已破坏其格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!