asp.net (C #) to implement a one-time dynamic upload more than one picture of the code (multiple files) _ Practical skills

Source: Internet
Author: User
Tags httpcontext
When doing asp.net web development, we often encounter the need to upload multiple files at once. Usually our solution is to put a number of uploaded file boxes fixed, such a solution is obviously unreasonable, because one upload multiple, it means that the number is uncertain. So we have to let these file upload box dynamically add, below I do a picture library management in the upload image function as an example

First look at the effect:
Open Initial Interface:

The default is to upload a picture, but when we click the "Add Picture" button can be implemented to select multiple pictures and its description at the same time upload, this feature limit can only upload 8, and each picture size does not exceed 1M, this can be changed according to the actual situation!
As shown in figure:


The following is the implementation process:
The first step is to use JavaScript code implementation to dynamically add the File upload box and description text box, the key code is as follows:
Copy Code code as follows:

<script type= "Text/javascript" >
var i=1
function AddFile ()
... {
if (i<8)
... {var str = ' <BR> <input type= "file" name= "file" runat= "server" style= "width:300px"/> Description: <input name= "text "Type=" text "style=" width:150px "maxlength="/> '
document.getElementById (' MyFile '). insertAdjacentHTML ("BeforeEnd", str)
}
Else
... {
Alert ("You can upload up to 8 photos at a time!") ")
}
i++
}
The </script>html calling code is:
<p id= "MyFile" ><input onclick= "AddFile ()" type= "button" value= "Add picture (add)" ><br
<input type= "File" name= "file" runat= "server" style= "width:300px"/>

Description: <input name= "text" type= "text" style= "width:150px" maxlength= "/>"
Step two: Server-side code implementation
Upload a single file or picture, so that the most common, but for such a one-time upload multiple files and their corresponding description of the problem, it will cost a bit of trouble
First of all The System.Web.HttpContext.Current.Request.Files method gets the file collection of the client, then obtains the Description text box collection through the Request.Form method, finally uploads the file with a loop and saves the corresponding information to the database
The key code is as follows:
Copy Code code as follows:

System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
string[] rd = request.form[1]. Split (', ');//Get a picture description of the text box string array, for the corresponding picture description
String Albumid=ddlalbum.selectedvalue.trim ();
int ifile;
for (ifile = 0; ifile < files. Count; ifile++)
... {
if (files[ifile). Filename.length > 0)
... {
..//Upload a single file and save the relevant information, ....//uploading individual files and saving
}
}

Finally, the full code of the above functions is given:
HTML code:
Copy Code code as follows:

<%...@ Page language= "C #" codefile= "UploadImg.aspx.cs" inherits= "netadmin_apicture_uploadimg"%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title> Untitled Page </title>
<script type= "Text/javascript" ....
var i=1
function AddFile ()
... {
if (i<8)
... {var str = ' <BR> <input type= "file" name= "file" runat= "server" style= "width:300px"/> Description: <input name= "text "Type=" text "style=" width:150px "maxlength="/> '
document.getElementById (' MyFile '). insertAdjacentHTML ("BeforeEnd", str)
}
Else
... {
Alert ("You can upload up to 8 photos at a time!") ")
}
i++
}
</script>
<link href= "Http://www.cnblogs.com/NetAdmin/Site.Css" rel= "stylesheet" type= "Text/css"/>
<body style= "Background-image:url" (... /images/bg.jpg); Text-align:center ">
<form id= "Form1" runat= "Server" >
<div>
<table id= "Table1" align= "center" border= "0" cellpadding= "1" cellspacing= "1" class= "table"
Style= "height:58px" width= "620" >
<tr>
&LT;TD align= "center" background= ". /images/topbg1.jpg ">
<font color= "#0000ff" face= "Song Body" size= "3" ><strong> upload picture </strong></font></td>
</tr>
<tr>
&LT;TD align= "center" >
</td>
</tr>
<tr>
&LT;TD align= "center" >
<asp:panel id= "Panel5" runat= "Server" width= "608px" >
<table width= "100%" >
<tr>
&LT;TD align= "Right" style= "width:100px" >
</td>
&LT;TD align= "Left" >
Note: Click to add Picture button can upload more than one picture, for each picture can write a sentence of no more than 20 words description. Single picture size is not larger than 1024k</td>
</tr>
<tr>
&LT;TD align= "Right" style= "width:100px" >
Please choose Picture: <br/>
</td>
&LT;TD align= "left" ><p id= "MyFile" ><input onclick= "AddFile ()" type= "button" value= "Add picture (add)" ><br />
<input type= "File" name= "file" runat= "server" style= "width:300px"/>
Description: <input name= "text" type= "text" style= "width:150px" maxlength= "/>"
</td>
</tr>
<tr>
&LT;TD align= "Right" style= "width:100px" >
Uploaded to the gallery:</td>
&LT;TD align= "Left" >
<asp:dropdownlist id= "Ddlalbum" runat= "Server" datasourceid= "SqlDataSource1"
Datatextfield= "Albumname" datavaluefield= "albumID" >
</asp:dropdownlist><asp:sqldatasource id= "SqlDataSource1" runat= "Server" connectionstring= "<%$" Connectionstrings:webjakecs%> "
Selectcommand= "SELECT [albumID], [albumname] from [wb_album] ORDER BY [albumID] DESC" >
</asp:SqlDataSource>
</td>
</tr>
<tr>
&LT;TD align= "Right" style= "width:100px" >
</td>
&LT;TD align= "Left" >
<asp:button id= "Btnupload" runat= "Server" text= "Start uploading" onclick= "Btnupload_click"/>
</td>
</tr>
<tr>
&LT;TD align= "Right" style= "width:100px" >
</td>
&LT;TD align= "Left" >
<asp:label id= "lblmessage" runat= "Server" font-bold= "True" forecolor= "Red" ></asp:Label></td>
</tr>
</table>
</asp:Panel>
</td>
</tr>
<tr>
&LT;TD align= "center" >
<font face= "Song Body" ></font><font face= "song Body" > </font>
</td>
</tr>
<tr>
&LT;TD align= "center" >
<font face= "Song Body" ></font>
</td>
</tr>
</table>
</div>
</form>
</body>

Background code:
Copy Code code as follows:

Using System;
Using System.Data;
Using System.Configuration;
Using System.Collections;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;
Using System.IO;
public partial class NetAdmin_APicture_UploadImg:System.Web.UI.Page
... {
protected void Page_Load (object sender, EventArgs e)
... {
}
protected void Btnupload_click (object sender, EventArgs e)
... {
Lblmessage.text = "";
Lblmessage.visible = false;
System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
System.Text.StringBuilder strmsg = new System.Text.StringBuilder ("");
string[] rd = request.form[1]. Split (', ');//Get a picture description of the text box string array, for the corresponding picture description
String Albumid=ddlalbum.selectedvalue.trim ();
int ifile;
for (ifile = 0; ifile < files. Count; ifile++)
... {
if (files[ifile). Filename.length > 0)
... {
System.Web.HttpPostedFile postedfile = Files[ifile];
if (PostedFile. contentlength/1024 > 1024)//single file cannot be greater than 1024k
... {
strmsg. Append (Path.getfilename) (PostedFile. FileName) + "---not greater than 1024k<br>");
Break
}
String fex = Path.getextension (PostedFile. FileName);
if (Fex!= ". jpg" && fex!=). JPG "&& fex!=". gif "&& fex!=". GIF ")
... {
strmsg. Append (Path.getfilename) (PostedFile. FileName) + "---picture is not formatted, only JPG or gif<br>");
Break
}
}
}
if (strmsg. Length <= 0)//indicates picture size and format are OK
... {
The following is the Create gallery directory
String dirname = "Pic00" + DdlAlbum.SelectedValue.Trim ();
String dirpath = Server.MapPath ("Http://www.cnblogs.com/PicBase");
Dirpath = Dirpath + "\" + dirname;
if (directory.exists (dirpath) = = False)
... {
Directory.CreateDirectory (Dirpath);
}
Random ro = new Random ();
int name = 1;
for (int i = 0; i < files. Count; i++)
... {
System.Web.HttpPostedFile myFile = files[i];
String FileName = "";
String fileextention = "";
String picpath = "";
FileName = System.IO.Path.GetFileName (myfile.filename);
String Stro=ro. Next (100,100000000). ToString () +name. ToString ()//produces a random number for the newly named picture
String NewName =datetime.now.minute.tostring () + DateTime.Now.Second.ToString () +datetime.now.millisecond.tostring ( ) +stro;
if (Filename.length > 0)//There are files to perform the upload operation and then save to the database
... {
Fileextention = System.IO.Path.GetExtension (myfile.filename);
String Ppath = Dirpath + "\" + NewName + fileextention;
Myfile.saveas (Ppath);
string fjname = FileName;
Picpath = "Picbase" + "+" + dirname + "\" + NewName + fileextention;
}
AddPicture (Picpath, Rd[i], albumID)//Save picture information to database
if (name = = 1)//If the first picture is updated each time, update it to the cover of the album
... {
Upfirstimg (albumID, Picpath);
}
Name = name + 1;//variable to rename the rule
}
}
Else
... {
Lblmessage.text = strmsg. ToString ();
Lblmessage.visible = true;
}
}
private void AddPicture (string imgpath,string imgnote,string albumid)
... {
String sql = "Insert Wb_albumimges (Imgpath,imgnote,albumid) VALUES (' +imgpath+" ', ' +imgnote+ ', ' "+albumid+ ')";
DB MyDB = new db ();
MyDB. Runproc (SQL);
}
private void Upfirstimg (String albumid,string firstimg)
... {
String sql = "Update wb_album set firstimg= '" +firstimg+ "' where albumid=" +ALBUMID;
DB MyDB = new db ();
MyDB. Runproc (SQL);
}
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.