ASP. NET (C #) code for one-time dynamic upload of multiple images (multiple files)

Source: Internet
Author: User

We often encounter the need to upload multiple files at a time during asp.net Web development. Generally, our solution is to put multiple Upload File boxes in a fixed manner. This solution is obviously unreasonable, because uploading multiple files at a time means that the quantity is uncertain. Therefore, we need to add these file upload boxes dynamically. The following uses the image upload function in my image library management as an example.

First look at the effect:
Open the initial interface:

By default, an image is uploaded. However, when you click "add image", you can select multiple images and their descriptions to upload at the same time. This function allows you to upload up to eight images at a time, the size of each image cannot exceed 1 MB, which can be changed as needed!



The implementation process is as follows:
Step 1: use javascript code to dynamically Add a file upload box and a description text box. The key code is as follows:
Copy codeThe Code is 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 = "20"/>'
Document. getElementById ('myfile'). insertAdjacentHTML ("beforeEnd", str)
}
Else
...{
Alert ("you can upload up to 8 images at a time! ")
}
I ++
}
</Script> the HTML call code is:
<P id = "MyFile"> <INPUT onclick = "addFile ()" type = "button" value = "Add image"> <br/>
<Input type = "file" name = "File" runat = "server" style = "width: 300px"/>

Description: <input name = "text" type = "text" style = "width: 150px" maxlength = "20"/>
Step 2: server code implementation
It is most common to upload a single file or image. However, it takes a lot of effort to upload multiple files at a time and their corresponding descriptions.
First, use System. web. httpContext. current. request. obtain the file set of the client using the Files method, and then use the Request. the Form method obtains the set of description text boxes, uploads files in a loop, and saves the corresponding information to the database.
The key code is as follows:
Copy codeThe Code is as follows:
System. Web. HttpFileCollection files = System. Web. HttpContext. Current. Request. Files;
String [] rd = Request. Form [1]. Split (','); // string array of the text box for obtaining the image description, which is the description of the corresponding image
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 relevant information
}
}

Finally, we provide all the code for the above functions:
HTML code:
Copy codeThe Code is 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">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> No title 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 = "20"/>'
Document. getElementById ('myfile'). insertAdjacentHTML ("beforeEnd", str)
}
Else
...{
Alert ("you can upload up to 8 images at a time! ")
}
I ++
}
</Script>
<Link href = "http://www.cnblogs.com/NetAdmin/Site.Css" rel = "stylesheet" type = "text/css"/>
</Head>
<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>
<Td align = "center" background = "../images/topbg1.jpg">
<Font color = "# 0000ff" face = "" size = "3"> <strong> upload images </strong> </font> </td>
</Tr>
<Tr>
<Td align = "center">
</Td>
</Tr>
<Tr>
<Td align = "center">
<Asp: Panel ID = "Panel5" runat = "server" Width = "608px">
& Lt; table width = "100%" & gt;
<Tr>
<Td align = "right" style = "width: 100px">
</Td>
<Td align = "left">
Note: you can click the Add image button to upload multiple images at a time. You can enter a description of up to 20 words for each image. The size of a single image cannot exceed 1024 kb </td>
</Tr>
<Tr>
<Td align = "right" style = "width: 100px">
Select an image: <br/>
</Td>
<Td align = "left"> <P id = "MyFile"> <INPUT onclick = "addFile ()" type = "button" value = "Add image) "> <br/>
<Input type = "file" name = "File" runat = "server" style = "width: 300px"/>
Description: <input name = "text" type = "text" style = "width: 150px" maxlength = "20"/>
</Td>
</Tr>
<Tr>
<Td align = "right" style = "width: 100px">
Uploaded Image Library: </td>
<Td align = "left">
<Asp: DropDownList ID = "ddlAlbum" runat = "server" performanceid = "sqlperformance1"
DataTextField = "AlbumName" DataValueField = "AlbumID">
</Asp: DropDownList> <asp: SqlDataSource ID = "sqlperformance1" runat = "server" ConnectionString = "<% $ ConnectionStrings: WebJakeCS %>"
SelectCommand = "SELECT [AlbumID], [AlbumName] FROM [WB_Album] order by [AlbumID] DESC">
</Asp: SqlDataSource>
</Td>
</Tr>
<Tr>
<Td align = "right" style = "width: 100px">
</Td>
<Td align = "left">
<Asp: Button ID = "btnUpload" runat = "server" Text = "Start upload" OnClick = "btnUpload_Click"/>
</Td>
</Tr>
<Tr>
<Td align = "right" style = "width: 100px">
</Td>
<Td align = "left">
<Asp: Label ID = "lblMessage" runat = "server" Font-Bold = "True" ForeColor = "Red"> </asp: Label> </td>
</Tr>
</Table>
</Asp: Panel>
</Td>
</Tr>
<Tr>
<Td align = "center">
<Font face = ""> </font> <font face = ""> </font>
</Td>
</Tr>
<Tr>
<Td align = "center">
<Font face = ""> </font>
</Td>
</Tr>
</Table>
</Div>
</Form>
</Body>
</Html>

Background code:
Copy codeThe Code is 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 (','); // string array of the text box for obtaining the image description, which is the description of the corresponding image
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) // a single file cannot exceed 1024 KB
...{
Strmsg. Append (Path. GetFileName (postedfile. FileName) + "--- cannot exceed 1024 k <br> ");
Break;
}
String fex = Path. GetExtension (postedfile. FileName );
If (fex! = ". Jpg" & fex! = ". JPG" & fex! = ". Gif" & fex! = ". GIF ")
...{
Strmsg. Append (Path. GetFileName (postedfile. FileName) + "--- incorrect image format, only jpg or gif <br> ");
Break;
}
}
}
If (strmsg. Length <= 0) // The image size and format are correct.
...{
// Create an image library 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 (, 00000000). ToString () + name. ToString (); // generate a random number for the newly named Image
String NewName = DateTime. Now. Minute. ToString () + DateTime. Now. Second. ToString () + DateTime. Now. Millisecond. ToString () + stro;
If (FileName. Length> 0) // only files are available for upload and then saved 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 the image information to the database.
If (name = 1) // if the first image is updated each time, it is updated to the album art.
...{
UpFirstimg (albumid, PicPath );
}
Name = name + 1; // The variable used 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.