c# - 如何将多个图像上传到数据库中以获得相同的 ID 并显示到 gridview 中?
问题描述
我想为同一个 id 上传多张图片,我自己做,但问题是他们只得到我选择的最后一张图片,这样当我们尝试显示代码时,将显示相同的图片。
这是我的代码,
DataClassesDataContext dc = new DataClassesDataContext();
string constr = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
SqlDataAdapter sda;
DataSet ds1 = new DataSet();
protected void UploadFile(object sender, EventArgs e)
{
imgError.Visible = false;
int id = int.Parse(Request.QueryString["ERID"].ToString());
foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
{
if ((postedFile != null) && (postedFile.ContentLength > 0))
{
int iFileSize = postedFile.ContentLength;
if (iFileSize > 2097152)
{
imgError.Visible = true;
imgError.Text = "File Size Must be 2MB or less than..!";
}
else if (iFileSize <= 2097152)
{
imgError.Visible = false;
tmpSaveFile();
}
}
}
using (SqlConnection con = new SqlConnection(constr))
{
sda = new SqlDataAdapter("select FileName,Path from TmpImageStore where ERID='" + id + "'", con);
sda.Fill(ds1);
GridView1.DataSource = ds1;
GridView1.DataBind();
}
}
void tmpSaveFile()
{
int id = int.Parse(Request.QueryString["ERID"].ToString());
foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
{
int count = 0;
var data = (from t in dc.SplitExpenses where t.ERID == id select t).ToList();
string filename = Path.GetFileName(postedFile.FileName);
string FileExtension = Path.GetExtension(postedFile.FileName);
string newFileName = "", locationCode = "", filePath = "";
if (data.Count > 0)
{
Thread.Sleep(100);
for (int i = 1; i <= data.Count; i++)
{
postedFile.SaveAs(Server.MapPath("~/InvoiceUploads/") + "Invoice " + id + "_" + i + FileExtension);
}
foreach (var x in data)
{
locationCode = x.Location_Code;
count = count + 1;
newFileName = "Invoice " + id + "_" + count + FileExtension;
filePath = Server.MapPath("~/InvoiceUploads/") + "Invoice " + id + "_" + count + FileExtension;
string contentType = postedFile.ContentType;
using (Stream fs = postedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
con.Open();
string query = "insert into TmpImageStore (FileName,ContentType,Path,ERID)values('" + newFileName + "', '" + contentType + "', '" + filePath + "', '" + id + "')";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.InsertCommand = new SqlCommand(query, con);
adapter.InsertCommand.ExecuteNonQuery();
cmd.Dispose();
con.Close();
}
}
}
}
}
}
在这里我还提供了我的 html 代码,我可以帮助你,
<div class="box">
<div class="box-header">
<h2>Invoice Upload
</h2>
</div>
<div class="padding">
<div class="row">
<div class="col-6 col-md-8">
<div class="p-3">
<ol class="breadcrumb white" style="color:#fd9c03;font-size:15px;padding:.20rem .5rem;">
<li class="breadcrumb-item"><i class="fa fa-warning"></i> Upload Upto 2MB Image/Document and must be use JPG/JPEG/PNG/PDF format!</li>
</ol>
</div>
</div>
</div>
<div class="row">
<div class="col-6 col-md-6">
<div class="p-3">
<asp:FileUpload ID="FileUpload1" runat="server" CssClass="btn btn-outline btn-rounded b-success text-success" AllowMultiple="true"/>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ForeColor="Red"
ControlToValidate="FileUpload1" Display="Dynamic" ErrorMessage=" Invalid Image Format..!" ValidationExpression="^.+(.jpg|.JPG|.jpeg|.JPEG|.PNG|.png|.pdf|.PDF)$">
</asp:RegularExpressionValidator>
<asp:Label ID="imgError" runat="server" Visible="false" ForeColor="Red" Font-Size="Large"></asp:Label>
</div>
</div>
<div class="col-6 col-md-3">
<div class="p-3">
<asp:Button ID="btnUpload" OnClick="UploadFile" runat="server" Text="Upload" CssClass="md-btn md-raised mb-2 w-xs green" />
</div>
</div>
</div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowHeader="false">
<Columns>
<asp:TemplateField HeaderText="Preview Image">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl='<%# Eval("Path")%>'
Width="100px" Height="100px" Style="cursor: pointer" OnClientClick="return LoadDiv(this.src);" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FileName" />
</Columns>
</asp:GridView>
</div>
</div>
而且还有另一个问题是图像没有显示在gridview中,我知道问题是它们获得了图像的完整路径但是当我自定义提供像“~/InvoiceUpload/ABC_1.jpg”这样的路径时,这将显示我的形象。
这是我的数据库表,
CREATE TABLE [dbo].[TmpImageStore] ( [TI] NUMERIC (18) IDENTITY (1, 1) NOT NULL, [FileName] VARCHAR (MAX) NULL, [ContentType] NVARCHAR (MAX) NULL, [Path] VARCHAR (MAX) NULL, [ERID] NUMERIC (18) NULL, PRIMARY KEY CLUSTERED ([TI] ASC) );
请任何人帮我解决这个问题。
谢谢你。
解决方案
您应该创建另一个与原始表有关系的表。例如:
CREATE TABLE [dbo].[TmpImageStore] (
[TI] NUMERIC (18) IDENTITY (1, 1) NOT NULL,
[KeyA] NUMERIC(18)
[FileName] VARCHAR (MAX) NULL,
[ContentType] NVARCHAR (MAX) NULL,
[Path] VARCHAR (MAX) NULL,
[ERID] NUMERIC (18) NULL,
PRIMARY KEY CLUSTERED ([TI] ASC)
);
CREATE TABLE [dbo].[Test] (
[KeyA] NUMERIC (18) IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (MAX) NULL
);
推荐阅读
- java - 如何从 rx.Observable 解压
- http - http(s) Youtube 中的 DELETE 和 PUT 方法
- regex - 只用几个分隔符拆分字符串一次
- angular - 提交表单后如何清除mat错误的验证错误
- user-interface - 如何在 SwiftUI 中使模态不可关闭
- docker - 使用变量作为参数标记 docker 图像时出错
- powershell - Powershell 问题:如何检查密码是否已实施
- docker - 主机名和服务名有什么区别?
- python - 使用 CPLEX 在 Python 上拨打骑行问题
- elasticsearch - 弹性搜索问题中的完全匹配查询