最近项目需要做电子签章,需要网页打开PDF签章后保存:正好复习哈二进制和流的转换:
文件转换成二进制字符串写入HTTP输出流
protected void Page_Load(object sender, EventArgs e)
{
try
{
string path = "Tett.PDF"; //获取文件名
path = Server.MapPath(path); //获取物理文件路径
if (File.Exists(path) == false)
throw new Exception("找不到PDF文件");
FileStream fs = File.Open(path, FileMode.Open);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, , buffer.Length);
fs.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "filename=pdf");
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
catch (Exception exp)
{
throw new Exception("错误", exp);
}
finally
{
Response.Flush();
Response.Close();
Response.End();
}
}
获取HTTP传入的实体内容保存文件
string path = "Test.PDF";
path = Server.MapPath(path);
if (File.Exists(path) == false)
throw new Exception("找不到PDF文件");
using (var inputStream = Request.InputStream)
{
using (var flieStream = new FileStream(path, FileMode.Create))
{
//从当前流中读取所有字节并将其写入到目标流中
inputStream.CopyTo(flieStream);
}
}
二进制转换成图片
/// <summary>
/// 二进制转换成图片
/// </summary>
/// <param name="Bytes"></param>
/// <returns></returns>
public static Bitmap BytesToBitmap(byte[] Bytes)
{
MemoryStream stream = null;
try
{
stream = new MemoryStream(Bytes);
return new Bitmap((Image)new Bitmap(stream));
}
catch (ArgumentNullException ex)
{
throw ex;
}
catch (ArgumentException ex)
{
throw ex;
}
finally
{
stream.Close();
}
}
图片转换成二进制
/// <summary>
/// 图片转换成二进制
/// </summary>
/// <param name="Bitmap"></param>
/// <returns></returns>
public static byte[] BitmapToBytes(Bitmap Bitmap)
{
MemoryStream ms = null;
try
{
ms = new MemoryStream();
Bitmap.Save(ms, Bitmap.RawFormat);
byte[] byteImage = new Byte[ms.Length];
byteImage = ms.ToArray();
return byteImage;
}
catch (ArgumentNullException ex)
{
throw ex;
}
finally
{
ms.Close();
}
}
流转换成文件
using (FileStream fs = new FileStream(path, FileMode.Create))
{
byte[] bytes = new byte[stream.Length];
int numBytesRead = ;
int numBytesToRead = (int)stream.Length;
stream.Position = ;
while (numBytesToRead > )
{
int n = stream.Read(bytes, numBytesRead, Math.Min(numBytesToRead, int.MaxValue));
if (n <= )
{
break;
}
fs.Write(bytes, numBytesRead, n);
numBytesRead += n;
numBytesToRead -= n;
}
fs.Close();
}
文件转换成流
/// <summary>
/// 从文件读取 Stream
/// </summary>
public Stream FileToStream(string fileName)
{
// 打开文件
FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
// 读取文件的 byte[]
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes, , bytes.Length);
fileStream.Close();
// 把 byte[] 转换成 Stream
Stream stream = new MemoryStream(bytes);
return stream;
}