1.把一个文件转换成二进制流
string FilePath= toFileFullPath + NewsID + "." + extension;
//判断文件是否存在 存在删除
if (File.Exists(FilePath))
{
File.Delete(FilePath);
}
_upfile.SaveAs(FilePath);
byte[] fileContent = ConvertFileToBytes(FilePath);
NewsFile objNewsFile = new NewsFile();
objNewsFile.Newsid = NewsID;
objNewsFile.Filecontent = fileContent;
objNewsFile.Filetype = "." + extension;
bool isResult = false;
isResult = datashowBll.InserFile(objNewsFile);
//文件转换成二进制流
public byte[] ConvertFileToBytes(string fileName)
{
if (File.Exists(fileName) == false) return null;
byte[] buffer = null;
FileStream fs = null;
try
{
fs = new FileStream(fileName, FileMode.Open);
buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
}
catch (Exception ex)
{
buffer = null;
throw;
}
finally
{
if (fs != null)
{
fs.Close();
fs = null;
}
}
return buffer;
}
2.把一个二进制流转换成文件,并下载
string toFileFullPath = HttpContext.Current.Server.MapPath("../News/file/");
path = toFileFullPath + NewsID + newsfile.Filetype;
if (newsfile != null)
{
if (File.Exists(path) == false)
{
FileStream fs = null;
BinaryWriter bw = null;
try
{
//二进制流转换成文件
byte[] content = newsfile.Filecontent;
fs = new FileStream(path, FileMode.CreateNew);
bw = new BinaryWriter(fs);
bw.Write(content, 0, content.Length);
}
catch (Exception ex)
{
//文件下载失败
}
finally
{
if (bw != null)
{
bw.Close();
bw = null;
}
if (fs != null)
{
fs.Close();
fs = null;
}
}
}
if (File.Exists(path))
{
System.IO.FileInfo file = new System.IO.FileInfo(path);
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.Buffer = false;
context.Response.ContentType = "application/octet-stream";
context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(newsfile.Title + newsfile.Filetype, System.Text.Encoding.UTF8));
context.Response.AppendHeader("Content-Length", file.Length.ToString());
context.Response.WriteFile(file.FullName);
context.Response.Flush();
context.Response.End();
}
}
return "";
菜鸟总结 多存疏漏 感谢指正