您的位置:首页 > 数据库

ASP.NET(C#) 多图上传至数据库及显示

2010-08-20 23:16 513 查看
前段时间做供求信息网的时候,发布新闻时需要用到图片上传功能,一条新闻记录会有多个图片,可以另外建立一张数据库表存放图片的地址还有记录ID,在这里我使用的是另外一种方法,新闻记录表设置一个pic字段,数据类型是nvarchar(max),图片路径以|隔开,

例img1.jpg|img2.jpg|……。

数据库表设计如下:
tb_news

int id 自增
nvarchar(max) pic 图片存储路径

图片上传部分:

控制每张图片大小最大为512k,格式仅限jpg,gif,bmp,最多上传6张,图片标题即图片的名称,可自行修改相应代码。

前台代码(pic.aspx):

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="pic.aspx.cs" Inherits="ASP.net.pic" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
var i = 1;
function addFile() {
if (i < 6) {
var str = '<BR> <input type="file" name="File" runat="server" style="width: 300px"/>'
document.getElementById('MyFile').insertAdjacentHTML("beforeEnd", str);
}
else {
alert("您一次最多只能上传6张图片!");
}
i++;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
请您选择您要上传的图片:<br />
<p id="MyFile" />
<input onclick="addFile()" type="button" value="增加图片" /><br />
<br />
<input type="file" name="File" style="width: 300px" />
<asp:Button ID="btnUpload" runat="server" Text="开始上传" OnClick="btnUpload_Click" />
<asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label>
</div>
</form>
</body>
</html>


后台代码(pic.aspx.cs):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace ASP.net
{
public partial class pic : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblMessage.Visible = false;
}

/// <summary>
/// 上传照片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpload_Click(object sender, EventArgs e)
{
lblMessage.Visible = true;
string FileName = "", PicPath = "";
int ifile;
System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
System.Text.StringBuilder strmsg = new System.Text.StringBuilder("");
for (ifile = 0; ifile < files.Count; ifile++)
{
if (files[ifile].FileName.Length > 0)
{
System.Web.HttpPostedFile postedfile = files[ifile];
if (postedfile.ContentLength / 1024 > 512)//单个文件不能大于512k
{
strmsg.Append(Path.GetFileName(postedfile.FileName) + "不能大于512k!<br>");
break;
}
string fex = Path.GetExtension(postedfile.FileName);
if (fex != ".jpg" && fex != ".JPG" && fex != ".gif" && fex != ".GIF" && fex != ".bmp" && fex != ".BMP")
{
strmsg.Append(Path.GetFileName(postedfile.FileName) + "图片格式仅支持jpg,gif,bmp!<br>");
break;
}
}
else
{
strmsg.Append("没有图片!");
break;
}
}
if (strmsg.Length <= 0)//图片大小和格式都没问题
{
//创建图库目录
string dirname = "pic";
string dirpath = Server.MapPath("/");
dirpath = dirpath + @"/" + dirname;
if (Directory.Exists(dirpath) == false)
{
Directory.CreateDirectory(dirpath);
}
for (int i = 0; i < files.Count; i++)
{
System.Web.HttpPostedFile myFile = files[i];
FileName = System.IO.Path.GetFileName(files[i].FileName);
if (FileName.Length > 0)//存在上传文件
{
string ppath = dirpath + @"/" + FileName;
myFile.SaveAs(ppath);
PicPath += FileName + "|";//拼接图片目录
}
}
AddPicture(PicPath);
}
else
{
lblMessage.Text = strmsg.ToString();
}
}

/// <summary>
/// 将图片路径保存到数据库
/// </summary>
/// <param name="imgpath"></param>
private void AddPicture(string imgpath)
{
string sql = "insert into tb_pic values('" + imgpath + "')";
dataCon dc = new dataCon();//dataCon是一个数据库操作管理类,可自己书写
dc.open();
if (dc.insert(sql) > 0)();//insert(sql)一个执行数据插入操作,可自己书写
{
lblMessage.Text = "成功!";
}
else
{
lblMessage.Text = "失败!";
}
dc.close();
dc.dispose();
}
}
}


效果如下:



显示图片部分:

前台代码(showPic.aspx):

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="showPic.aspx.cs" Inherits="ASP.net.showPic" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>


后台代码(showPic.aspx.cs):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

namespace ASP.net
{
public partial class showPic : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.showPics();
}

private void showPics()
{
string sql = "select pic from tb_news where id=1";
string path = "",title="";
string[] img;
dataCon dc = new dataCon();
dc.open();
SqlDataReader dr = dc.query(sql);
while (dr.Read())
{
path = (string)dr["path"];
}
img = path.Split('|');
int i=0,j=img.Length;
for (i = 0; i < j-1; i++)
{
Response.Write("<img src="/" mce_src="/""pic//" + img[i].ToString() + "/"/><br/>");
title = img[i].Substring(0,img[i].ToString().IndexOf('.'));
Response.Write("图"+i+" "+title+"<br/>");
}
}
}
}


效果如下:



可以设置相应的css文件控制图片的显示位置,让它看起来更加美观,在这里只是简述最基本的功能。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: