asp.net 下载任意格式文件 上传文件后台代码
思路:将文件转化为流,输出到页面上的iframe中去
//下载附件逻辑
object DownLoad(NameValueCollection nv)
{
int attachId = nv["attachid"].ToInt();
SmalLessonAttach attachment = SmalLessonAttach.Get(attachId);
if (attachment == null)
{
return new {code=-1,msg="附件不存在!"};
}
string fileName = attachment.Name;
string filePath = Path.Combine(FileUtil.FormatDirectory(ConfigBase.GetConfig("doc")["file_root"]), attachment.Path, attachment.AttachmentId, attachment.Name);
if (!File.Exists(filePath))
return new {code = -2, msg = "附件不存在!"};
//以字符流的形式下载文件
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
jc.Context.Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
jc.Context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
jc.Context.Response.BinaryWrite(bytes);
jc.Context.Response.Flush();
jc.Context.Response.End();
return new {code=1};
}
//上传附件逻辑
int UploadAttachment(NameValueCollection nv)
{
//微课不存在返回
int playid = nv["playid"].ToInt();
if (SmalLesson.Get(playid) == null) return -3;
//从这里开始保存附件
var files = httpContext.Request.Files;
if (files.Count == 0) return -1;
var file = files[0];
if (file.ContentLength == 0) return -2;
string root = ConfigBase.GetConfig("doc")["file_root"];
string dir = string.Format("Upload/weike/{0}", DateTime.Now.ToString("yy/MM/dd"));
string weiId = StringUtil.UniqueId();
string savePath = Path.Combine(root, dir, weiId);
if (!Directory.Exists(savePath))
Directory.CreateDirectory(savePath);
string fileName = Path.Combine(savePath, file.FileName);
file.SaveAs(fileName);
ILinqContext<SmalLessonAttach> cx = SmalLessonAttach.CreateContext(false);
SmalLessonAttach attachment = new SmalLessonAttach();
attachment.PlayId = playid;
attachment.Name = file.FileName;
attachment.UserId = LoginUser.FGuid;
attachment.Doctype = Path.GetExtension(file.FileName);
attachment.DateCreated = DateTime.Now;
attachment.AttachmentId = weiId;
attachment.Path = dir;
attachment.SchoolId = LoginUser.Schoolid;
cx.Add(attachment, true);
cx.SubmitChanges();
return 1;
}
var file = new FileInfo(filePath); //得到文件
if (file.Exists) //判断文件是否存在
{
jc.Context.Response.Clear(); //清空Response对象
/*设置浏览器请求头信息*/
jc.Context.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); //指定文件
jc.Context.Response.AddHeader("Content-Length", file.Length.ToString()); //指定文件大小
jc.Context.Response.ContentType = "application/application/octet-stream"; //指定输出方式
jc.Context.Response.WriteFile(file.FullName); //写出文件
jc.Context.Response.Flush(); //输出缓冲区(刷新Response对象)
jc.Context.Response.Clear(); //清空Response对象
jc.Context.Response.End(); //结束Response对象
}
导出文件不能用post或者get来导出,必须是url请求
posted on 2014-05-19 15:19 huakaiyueluo 阅读(360) 评论(0) 编辑 收藏 举报