asp.net multiple attachment Upload Implementation Code _ Practical skills

Source: Internet
Author: User
But the basic premise is in advance through the JS script to create the DOM dynamically, and then upload the server to do some processing, a bit similar to 163 of the mail system. File uploads need to be submitted through the Post method of the page, which I have explained in a question that has been addressed in a strange problem with the IFrame form submission in MOSS development, including how to use the hidden iframe of the page to submit the form to prevent the page from being submitted to the server and causing the pages to refresh. The principle of multiple attachment upload is similar, only need to be in advance through the script on the page dynamically create multiple input type= ' file ' label, of course, if you want to function more perfect, you may also need to dynamically add some button events through the script to allow users to delete the files he added. Below is a screenshot of the application effect.

The contents of the red box are created dynamically on the page by the script, adding the user's file name to a div dynamically in the client's selected files, and putting a hidden input type= in the Div. File ' 's tag, its value is the path of the user's chosen file, and then place an img in the Div, adding onmouseover and onmouseout events to add some mouse-sliding effects to the picture, and the onclick event is used in response to the user clicking on IMG to delete the corresponding file 。 Look at the concrete implementation in the code.

Copy Code code 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 ">
<title></title>
<script src= "Multiaffix.js" type= "Text/javascript" ></script>
<script type= "Text/javascript" >
var controlname = 1; This variable was 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 (' Your have already added this image! ');
if (oldbrowser!= undefined) {
var newbrowser = Oldbrowser.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_rollover.gif ';
}
Newfileimgbutton.onmouseout = function () {
THIS.SRC = ' shoutout_close.gif ';
}

Browseimgelement.replacechild (Newbrowser, Oldbrowser);
Oldbrowser.name = ++controlname;
Oldbrowser.style.display = ' None ';
Newfile.appendchild (Oldbrowser);

Newfile.appendchild (Newfileimgbutton);
Targetelement.appendchild (NewFile);

$get ("Chkagree"). Checked = false;
$get ("Btadd"). Disabled = true;
Savestatselement.value + = filename + ' | ';
}
}
</script>

<body>
<form id= "Form1" runat= "Server" >
<asp:scriptmanager id= "ScriptManager1" runat= "Server" >
</asp:ScriptManager>
<div>
<div>
Description:
Id= "Tbdescription" maxlength= "<asp:textbox" 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>
Notify Shout out User:
<asp:checkbox id= "Chknotifyuser" runat= "Server"/>
</div>
<div>
Notify shout out to Email:
<asp:textbox id= "Tbshoutouttoemail" maxlength= "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 should not exceed
200px.</div>
<div>
<input id= "Chkagree" type= checkbox "onclick=" $get (' Btadd '). disabled=!this.checked; "/>i
Agree.legal signoff text to is 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>

Copy Code code 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, test passed!

Simple description:

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

2. Btaddimage will be disabled off after being clicked, and then display Saveshoutoutaddimgs entire Div.

3. In Saveshoutoutaddimgs, the user can complete the file selection and confirmation operation, Chkagree used to enable the Btadd button.

4. When the user clicks on the Btadd, the onclick event is triggered, which is registered in the Code-behind Page_Load method because it is convenient to write in the script that involves using the ClientID property of the server-side control.

5. The client function addimg is used to complete the add operation of the dynamic DOM, which receives three parameters, the first parameter targetelement represents the host div that holds the dynamic DOM, and the second parameter savestatselement represents a hidden text box for saving the added file information , the third parameter oldimgelement represents the file information hidden text box that was used to save the user's last upload in edit state. The basic idea is to copy the input type= "file" tab under Browseimg, and then add the dynamically generated DOM to the Saveshoutoutimgs and attach some events at the same time.

6. The Tbimgs hidden text box is used to save information about the user's selected files, in the format of "| file name 1| filename 2| filename 3| ..."; Tboldimgs hidden text box values are not available in edit state, which saves information about the user's previous uploaded file. The storage format is the same as Tbimgs.

7. In the editing state, add the same label to the SAVESHOUTOUTIMGS tag as the dynamic DOM generated by the Addimg script function on the service side and write the file information to the Tboldimgs hidden text box at the same time. I've written an example here where readers can refine their code to validate. When I display a file, I add a link to the name of the file, which points to a page that outputs a picture, such as retrieving the binary data of a picture from the database and then write it to the page by the resulting picture ID. Imageentity is the entity class for custom image objects to store information about picture files.
Copy Code code 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_rollover.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;}
}

There's a problem to be aware of, when you save the data in the editing state, you need to remove the original picture and then add the picture again on the server side, then you need to retrieve the picture data by Tboldimgs the information in the hidden field before you save the data, and then save the picture again. For example, the edit state gets a, B, C three pictures, the user deleted the picture C, added a picture D, save on the service side of the operation: first through the Tboldimgs hidden field to get the rest of the old picture information (that is, pictures A and B), from the database to retrieve the data of these pictures, Before saving, delete all uploaded pictures associated with this piece of data, and then save it in the database with the new picture (that is, picture D).

Another thing is, if you want to upload the picture before the image file size, must be implemented through C # code, this can not simply through the JS script to achieve, because it involves the browser to the client file access restrictions. In other words, the page needs to be submitted to the server, to determine the completion of the notification after the client's behavior, in order to avoid page submission when the client's original state is lost, you can use the way to hide the IFRAME submission page, this in the beginning of the article I have mentioned.

In short, implementing multiple attachment uploads in the web must be dynamically created using JavaScript to create the DOM, which can be added to the page on the server side with a previously processed DOM, and also attach script events, and note the state of each control between the server-side code and the 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.