您的位置:首页 > 编程语言 > C#

经验分享:C#上传图片转Base64字节存库并支持转换文件提供url读取

2013-09-03 18:46 966 查看
工作中经常需要用到图片上传功能,传统的存服务器目录方式在服务器迁移、部署和各种平台交互时操作不太方便,而图片资源存数据库是相对比较方便维护的方式了!以下贴出用C#存储和读取图片资源的一些方法:

/* ----------------------------------------------------------------------------
* 上传图片类
* 先读取图片资源转换成base64字节,再转换成字符串存库,无需上传文件到服务器目录
* ----------------------------------------------------------------------------
*/

using System.IO;

/*
* 提交数据部分
*/
int l = file_img1.PostedFile.ContentLength;
byte[] buffer = new byte[l];
Stream s = file_img1.PostedFile.InputStream;
try
{
s.Read(buffer, 0, l);
string imgByte = Convert.ToBase64String(buffer);
}
catch (Exception ex)
{
s.Close();
s.Dispose();

throw ex;
}
finally
{
s.Close();
s.Dispose();
}

string sqlText = string.Format("insert into tb_image(id,imgByte) values({0},'{1})", id, imgByte);
//保存到数据库...

/* ----------------------------------------------------------------------------
* 读取图片类
* 先从库里读取字符串,再转换成base64字节,通过文件输出流生成图片文件供url读取
* ----------------------------------------------------------------------------
*/
using System.IO;

string imgByte = ...//从库里读取数据赋值
//取得数据转换base64字节
byte[] buffer = Convert.FromBase64String(imgByte);
//定义图片文件保存目录及文件名
string imgPath = System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "images\\demo\\imgfile_1.jpg";
if(!File.Exists(imgPath))
{
//定义输出流对象
FileStream fs = new FileStream(imgPath, FileMode.Create);
fs.Write(buffer, 0, (int)buffer.Length);
fs.Close();
}
//图片文件已成功输出,记住此图片相对路径供url访问
string domainPath = "../images/demo/imgfile_1.jpg";
//网页上图片即可访问此url:domainPath
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  asp.net 图片上传
相关文章推荐