ASP. NET multi-attachment upload implementation code

Source: Internet
Author: User

But the basic premise is to use the js script to dynamically create the DOM, and then perform processing on the server during the upload, which is a bit similar to the 163 mail system. File Upload needs to be submitted through the POST method on the page. This is an odd problem that I have fixed in solving iFrame form submission in MOSS development, this includes how to use the iFrame hidden in the page to submit a form to avoid page refresh caused by the whole page being submitted to the server. The principle of multi-attachment upload is similar, but you only need to dynamically create multiple input type = 'file' tags on the page through the script in advance. Of course, if you want to be more functional, you may also need to dynamically Add button events through scripts so that users can delete the files they have added. The following is an application effect.

The content in the red box is dynamically created through the script on the page, and the file name of the file selected by the user on the client is dynamically added to a div, at the same time, place a hidden input type = 'file' tag in this div. Its value is the path of the selected file, and then place an img In the div, the onmouseover and onmouseout events increase the effect of moving the mouse over the image. The onclick event is used to delete the corresponding file when the user clicks img. Let's take a look at the specific implementation in the code.

Copy codeThe Code is as follows: <% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "Default. aspx. cs" Inherits = "WebApplication1. _ Default" %>

<! 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 src = "MultiAffix. js" type = "text/javascript"> </script>
<Script type = "text/javascript">
Var controlName = 1; // This variable is for the dynamic file controls's name.

Function addImg (targetElement, savestatsElement, oldimgElement ){
Var browseimgElement = $ get ("browseimg ");
Var arr = browseimgElement. getElementsByTagName ('input ');
If (arr. length = 0 | arr [0]. value. length = 0 ){

Alert ('no file inputs .');
Return;
}
Var oldbrowser = arr [0];
Var filename = getfilename (oldbrowser. value );
If (! Validateimgtype (oldbrowser. value) return;
If (! Validateimgcount (targetElement, 3) return;
Var imgtitles = savestatsElement. value + oldimgElement. value;
If (validateimgexist (filename, imgtitles) {alert ('you have already added this image! '); Return ;}
If (oldbrowser! = Undefined ){
Var newbrowser = oldbrode. cloneNode (true );
Newbrowser. value = '';
Var newfile = document. createElement ('div ');
Newfile. innerHTML = filename + '';

// Create a button element for delete the image.
Var newfileimgbutton = document. createElement ('img ');
Newfileimgbutton. src = 'ShoutOut_Close.gif ';
Newfileimgbutton. alt = 'delete ';
Newfileimgbutton. onclick = function (){
This. parentNode. parentNode. removeChild (this. parentNode );
SavestatsElement. value = updatehiddenimgs (filename, savestatsElement. value );
}
Newfileimgbutton. onmouseover = function (){
This. src = 'shoutout_close_rolover.gif ';
}
Newfileimgbutton. onmouseout = function (){
This. src = 'ShoutOut_Close.gif ';
}

BrowseimgElement. replaceChild (newbrowser, oldbrochild );
Oldbrowser. name = ++ controlName;
Oldbro'. style. display = 'none ';
Newfile. appendChild (oldbrochild );

Newfile. appendChild (newfileimgbutton );
TargetElement. appendChild (newfile );

$ Get ("chkAgree"). checked = false;
$ Get ("btAdd"). disabled = true;
SavestatsElement. value + = filename + '| ';
}
}
</Script>

</Head>
<Body>
<Form id = "form1" runat = "server">
<Asp: ScriptManager ID = "ScriptManager1" runat = "server">
</Asp: ScriptManager>
<Div>
<Div>
Description:
<Asp: TextBox ID = "tbDescription" MaxLength = "2000" runat = "server" TextMode = "MultiLine"> </asp: TextBox>
</Div>
<Div>
Location:
<Asp: DropDownList ID = "ddlLocation" runat = "server">
</Asp: DropDownList>
</Div>
<Div>
Display Posted By User:
<Asp: CheckBox ID = "chkPostedByUser" Checked = "true" runat = "server"/>
</Div>
<Div>
Y Shout out User:
<Asp: CheckBox ID = "chkNotifyUser" runat = "server"/>
</Div>
<Div>
Notify Shout out to Email:
<Asp: TextBox ID = "tbShoutoutToEmail" MaxLength = "25" runat = "server"> </asp: TextBox>
</Div>
<Div>
Images:
<Div id = "saveshoutoutimgs" runat = "server">
</Div>
<Input id = "btAddImage" type = "button" onclick = "$ get ('saveshoutoutaddimgs '). style. display = 'block'; this. disabled = true ;"
Value = "Click here to Add Image"/>
</Div>
<Div id = "saveshoutoutdetailshowimg">
<Div id = "saveshoutoutaddimgs" style = "display: none;">
<Div>
Add Image: </div>
<Div id = "browseimg">
<Input type = "file"/>
</Div>
<Div>
Size limit of the images is 100kb. Hieght and Width of the images shocould not exceed
200px. </div>
<Div>
<Input id = "chkAgree" type = "checkbox" onclick = "$ get ('btadd'). disabled =! This. checked; "/> I
Agree. legal signoff text to be defined.
</Div>
<Div>
<Input id = "btAdd" disabled = "disabled" type = "button" value = "Add" runat = "server"/>
</Div>
</Div>
</Div>
</Div>
<Asp: TextBox ID = "tbImgs" runat = "server" Text = "|" Style = "display: none;"> </asp: TextBox>
<Asp: TextBox ID = "tbOldImgs" runat = "server" Text = "|" Style = "display: none;"> </asp: TextBox>
</Form>
</Body>
</Html>

Copy codeThe Code is as follows: protected void Page_Load (object sender, EventArgs e)
{
String script = string. format ("addImg ($ get ('{0}'), $ get ('{1}'), $ get ('{2 }'));",
This. saveshoutoutimgs. ClientID,
This. tbImgs. ClientID,
This. tbOldImgs. ClientID );
This. btAdd. Attributes. Add ("onclick", script );
}

The Code is based on Ajax.net. The environment is Visual Studio 2008 + Windows 2003. The test passes!

Here is a brief description:

1. <div id = "saveshoutoutimg" runat = "server"/> is used to store dynamically added file tags.

2. After btAddImage is clicked, it will be disabled and the entire div of saveshoutoutaddimgs will be displayed.

3. In saveshoutoutaddimgs, you can select and confirm the file. chkAgree is used to enable btAdd.

4. When you click btAdd, The onclick event is triggered. This event is registered in the code-behind Page_Load method, because the script involves using the ClientID attribute of the server control, which makes writing easier.

5. the client function addImg is used to add dynamic DOM. It receives three parameters. The first parameter targetElement indicates the host DIV that stores dynamic DOM, the second parameter savestatsElement indicates the hidden text box used to save the added file information, and the third parameter oldimgElement indicates the hidden text box used to save the last uploaded file information in the editing state. The basic idea is to copy the input type = "file" tag under browseimg, add the dynamically generated DOM to saveshoutoutimgs, and attach some events.

6. the tbImgs hidden text box is used to save the information of the selected file. It uses "| file name 1 | file name 2 | file name 3 |... "format storage; the value in the hidden tbOldImgs text box is displayed only after editing. The information of the last uploaded file is saved, and the storage format is the same as that of tbImgs.

7. In the editing status, add the same label as the dynamic DOM generated by the addImg script function to the saveshoutoutimgs tag on the server side, and Write File Information to the tbOldImgs hidden text box. I wrote an example here. Readers can complete the code for verification. When a file is displayed, I add a link to the file name. The page pointed to by this link is used to output images, for example, retrieve the binary data of the image in the database using the obtained image ID and Write it to the page. ImageEntity is the entity class of the custom Image object, used to store information about the Image file.Copy codeThe Code is as follows: public void SetImages (List <ImageEntity> images)
{
If (images. Count> 0)
{
This. tbOldImgs. Text = "| ";
Foreach (ImageEntity image in images)
{
HtmlGenericControl imgDiv = new HtmlGenericControl ("Div ");

HtmlAnchor imgAnchor = new HtmlAnchor ();
ImgAnchor. HRef = string. Format ("Thumbnail. aspx? Isthumbnail = false & basecommentid = {0} & imagetitle = {1 }",
Image. ID. ToString (), image. Title );
ImgAnchor. Target = "_ blank ";
ImgAnchor. Title = image. Title;
ImgAnchor. InnerHtml = image. Title + "";

HtmlImage imgButton = new HtmlImage ();
ImgButton. Src = "ShoutOut_Close.gif ";
ImgButton. Alt = "Delete ";
ImgButton. attributes ["onclick"] = string. format ("this. parentNode. parentNode. removeChild (this. parentNode); $ get ('{0 }'). value = updatehiddenimgs ('{1}', $ get ('{0 }'). value );",
This. tbOldImgs. ClientID, image. Title );
ImgButton. Attributes ["onmouseover"] = "this.src+'shoutout_close_rolover.gif '";
ImgButton. Attributes ["onmouseout"] = "this.src+'shoutout_close.gif '";

ImgDiv. Controls. Add (imgAnchor );
ImgDiv. Controls. Add (imgButton );
This. saveshoutoutimgs. Controls. Add (imgDiv );
This. tbOldImgs. Text + = image. Title + "| ";
}
}
}

Public class ImageEntity
{
Public ImageEntity ()
{
}

Public ImageEntity (int id, string title, Byte [] imageBlob, string type)
{
ID = id;
Title = title;
ImageBlob = imageBlob;
Type = type;
}

Public int ID {get; set ;}
Public string Title {get; set ;}
Public string Type {get; set ;}
Public Byte [] ImageBlob {get; set ;}
}

Note that when you save the edited data, you need to delete the original image on the server and then add the image again. For images not modified on the client, you need to re-retrieve the image data through the information in the tbOldImgs hidden field before saving the data, and then save the image again. For example, you can get three images A, B, and C in the editing status. If you delete image C and add image D, perform the following operations on the server: first, you can use the tbOldImgs hidden field to obtain the remaining old image information (image A and Image B) and retrieve the data of these images from the database, before saving the data, delete all uploaded images related to the data, and save them to the database together with the new image (that is, image D.

Another point is that if you want to determine the size of the image file before uploading an image, you must use the C # code. This cannot be implemented simply by using the js script, this is because browser restrictions on client file access are involved. That is to say, You need to submit the page to the server in advance to notify the client of the next behavior after the judgment is complete. To avoid the loss of the original status of the client when the page is submitted, you can use the iFrame-hidden mode to submit the page, I have mentioned this at the beginning of this article.

In short, the DOM must be dynamically created by using javascript For multi-attachment upload on the Web. In the editing status, the server can add the previously processed DOM to the page and add the script event at the same time, save the status of each control between the server code and client code.

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.