如何把网上的图片存储到数据库
我这边想要做到的是:搜索网络上的图片,找到其网址,转成数据流,存入数据库,我找了很多资料,才做成这样,能基本达到目的,但现在我有两个问题,由于我注释掉的那两句不知道什么原因不能成功转成有效的数据流,我只能把图片转存成文件之后再读取之后存储到数据库,这个很多余,如果我使用同样的文件名存储呢,那将造成一个扇区被反复多次擦写,磁盘寿命会有问题,那么第一个问题就是,我怎样将这个文件存储到虚拟盘中,意思就是在内存中,最简单的做法,还是搞定这个数据流(就是我注释掉的那一部分),让他可以直接调用,不需存储。第二个问题是,我感觉这个代码非常繁琐,请大家帮我看看怎么精简,这个是在ashx里面的代码
public int tp_cunchu(string tp_path, string sql, SqlConnection conn, HttpContext context) //存图片文件
{
Bitmap img = null;
HttpWebRequest req;
HttpWebResponse res = null;
//byte[] photo = null;
string path = "";
try
{
Uri httpUrl = new Uri(tp_path);
req = (HttpWebRequest)(WebRequest.Create(httpUrl));
req.Timeout = 10000;
//设置超时值
req.UserAgent = "XXXXX";
req.Accept = "XXXXXX";
req.Method = "GET";
res = (HttpWebResponse)(req.GetResponse());
img = new Bitmap(res.GetResponseStream());
//获取图片流
path = @"E:/tupian/" + DateTime.Now.ToFileTime().ToString() + ".jpg";
//随机名
img.Save(path);
context.Response.Write("wangzhi:" + tp_path + "\n");
//MemoryStream ms = new MemoryStream();
//photo = ms.ToArray();//.GetBuffer();
}
catch (Exception ex)
{
string aa = ex.Message;
}
finally
{
//res.Close();//哦,还有,为什么我的这个关闭会报错
}
int d = 0;
string str = "";
if (path != "")
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] photo = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
try
{
conn.Open();
SqlCommand com = new SqlCommand(sql, conn);
com.Parameters.Add("@photoBinary", SqlDbType.Binary, photo.Length);
com.Parameters["@photoBinary"].Value = photo;
//SqlDataReader dr= com.ExecuteReader();
d = Convert.ToInt32(com.ExecuteScalar());
str = "图片上传成功";
}
catch (Exception ex)
{
str = ex.Message.ToString();
}
finally
{
conn.Close();
}
}
return d;
}