Upload Image Code

Source: Internet
Author: User

An upload source code for ASP. NET image uploads >>>>>

Code 1:

If (this. fudsc. hasfile) // check whether a file exists
{
String fullfilename = This. fudsc. postedfile. filename; // file path name
String filename = fullfilename. substring (fullfilename. lastindexof ("//") + 1); // image name
String type = fullfilename. substring (fullfilename. lastindexof (".") + 1); // image format

If (type = "jpg" | type = "jpg" | type = "GIF" | type = "GIF" | type = "BMP" | type = "BMP ") // determine whether the image is of the image type
{
If (this. fudsc. postedfile. contentlength> 20*1024)
{
Response. Write ("<SCRIPT> alert ('upload image must be less than 20 KB! '); </SCRIPT> ");
}
Else
{
String Path = httpcontext. Current. Request. mappath ("~ /ZP/"); // obtain the path of the uploaded file's website directory
This. fudsc. saveas (path + filename); // store the file to the disk




Response. Write ("<SCRIPT> alert ('image uploaded successfully! '); </SCRIPT> "); // prompt

This. imgpicture. src = "~ /ZP/"+ filename; // display image
}

}
Else
{
Response. Write ("<SCRIPT> alert ('non-image type, not allowed to upload! '); </SCRIPT> ");
}
}
Else
{
Response. Write ("<SCRIPT> alert ('file must be specified! '); </SCRIPT> ");
}

Code 2:

 

Step 1:

Client >>>>

Figure: <input type = "text" id = "imgurl" name = "imgurl" onpropertychange = "onpropertychange_click (this, 'btnview '); "/> <input type =" button "id =" Upload "value =" Upload "onclick =" doupload (this, 'imgurl ',''); "/> <input type =" button "id =" btnview "name =" btnview "value =" preview "style = 'display: none; 'onclick = 'previewpic (this, 'imgurl', ''); '/>

 

The referenced JS script functions are as follows:

 

Function _ (OBJ ){

Return document. getelementbyid (OBJ );

}

 

Function onpropertychange_click (OBJ, btnview ){
If (typeof (btnview) = 'string ')
Btnview = _ (btnview );
If (typeof (OBJ) = 'string ')
OBJ = _ (OBJ );
If (btnview ){
If (obj. value! = ""){
If (btnview. style. Display = "NONE "){
Btnview. style. Display = '';
}
} Else {
If (btnview. style. Display = ""){
Btnview. style. Display = "NONE ";
}
}
}

}

 

Function doupload (OBJ, imgurl, Param ){
VaR url = "/accessories/useruploadfile/" + Param;
If (document. All ){
Showmodelessdialog (URL, window, "Help: No; Status: No; dialogwidth: 300px; dialogheight: 80px ;");}
Else {window. Open (URL );
}

}

 

Function previewpic (selfobj, imgobj, title ){
If (typeof (imgobj) = "string ")
Imgobj = _ (imgobj );
If (! Imgobj ){
Alert ("the image object control is invalid! ");
Return;
}
Imgurl = imgobj. value;
If (imgurl = NULL | imgurl = ""){
Alert ("invalid image address! ");
Return;
} If (imgurl. lastindexof (".") =-1 ){
Alert ("the image has no suffix! ");
Return;
}
VaR suffix = imgurl. substring (imgurl. lastindexof ("."). tolowercase (). Split (".") [1];
VaR mediacontainer = NULL;
If (suffix = "SWF "){
Mediacontainer = flash (window. Screen. Width, window. Screen. Height, imgurl, false );
} Else if (suffix = "GIF" | suffix = "jpg" | suffix = "Jpeg" | suffix = "BMP" | suffix =" PNG ") {
Mediacontainer = " ";
} Else {
Alert ("the address format is incorrect. The current supported formats are:/R/n SWF | GIF | JPG | jpe | JPEG | BMP | PNG"); return;
}

If (Title = NULL | Title = "")
Title = "image preview ";
VaR htmlstr = "<HTML>
VaR W = Window. open ();
Using Doc ument. Write (htmlstr );
Using Doc ument. Close ();
W. Focus ();


}

Function flash (W, H, Uri, istransparent ){
VaR transparent = "<Param name = 'wmode' value = 'transparent'/> ";
If (! Istransparent)
Transparent = '';
VaR F = "<object classid =/" CLSID: d27cdb6e-ae6d-11cf-96b8-444553540000 /"";
F + = "codebase =/" http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0 "";
F + = "width =/" "+ W +"/"Height =/" "+ H +"/"align =/" middle/"viewastext> ";
F + = "<Param name =/" allowScriptAccess/"value =/" samedomain/"/> ";
F + = "<Param name =/" movie/"value =/" "+ URI +"/"/> ";
F + = "<Param name =/" menu/"value =/" false/"/> ";
F + = "<Param name =/" Quality/"value =/" autohigh/"/> ";
F + = "<Param name =/" bgcolor/"value =/" # ffffff/"/>" + transparent;
F + = "<embed src =/" "+ URI +"/"menu =/" false/"Quality =/" autohigh/"width =/" "+ W +" /"Height =/" "+ H + "/"";
F + = "align =/" middle/"allowScriptAccess =/" samedomain/"type =/" application/X-Shockwave-flash /"";
F + = "pluginspage =/" http://www.macromedia.com/go/getflashplayer/ "/> </Object> ";
Return (f );
}

 

Step 2:

Source code of the server upload page >>>>

<HTML>
<Head>
<Title>
<% = (O. username) %>
File Upload </title>
<Base target = "_ Self">
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">
<Style type = "text/CSS">
Body {padding-Right: 0px; padding-left: 0px; font-size: 12px; padding-bottom: 0px; SCROLLBAR-HIGHLIGHT-COLOR: #808080; SCROLLBAR-SHADOW-COLOR: #808080; SCROLLBAR-3DLIGHT-COLOR: # d4d0c8; SCROLLBAR-ARROW-COLOR: #000000; padding-top: 0px; SCROLLBAR-TRACK-COLOR: # d4d0c8; SCROLLBAR-DARKSHADOW-COLOR: # d4d0c8; SCROLLBAR-BASE-COLOR: # d4d0c8; Background-color: # d4d0c8; text-align: center; magin: 0}
</Style>
<Script language = "JavaScript" src = "/JS/utility. js">

</SCRIPT>
<Meta name = "generator" content = "Microsoft Visual Studio. NET 7.1">
<Meta name = "code_language" content = "C #">
<Meta name = "vs_defaultclientscript" content = "JavaScript">
<Meta name = "vs_targetschema" content = "http://schemas.microsoft.com/intellisense/ie5">
<SCRIPT type = "text/JavaScript" Language = "JavaScript">
<! --

Function fngetinfo (){
VaR S = dialogarguments;
S. inputvalue = _ ("file1"). value;
S. fileupdate ();
}
-->
</SCRIPT>
</Head>
<Body ms_positioning = "gridlayout">
<Form ID = "form1" method = "Post" runat = "server">
<Br/>
<Div> select image: <input type = "file" name = "file1" id = "file1" runat = "server" size = "10"/>

<Asp: button id = "btnsubmit" runat = "server" text = "Upload"/> </div>
</Form>
</Body>
</Html>

 

Hide. CS files

 

 

Private void btnsubmit_click (Object sender, eventargs E)
{
If (this. file1.postedfile! = NULL)
{
String filename = This. file1.postedfile. filename. Trim ();
If (filename = "")
Return;
String resulturl;
String filetype = This. file1.postedfile. contenttype. Trim (). tolower ();
Int filesize = This. file1.postedfile. contentlength;
String clientpath = utility. getserverpath (O. userid, filename, filetype, out resulturl, null );
If (clientpath! = "")
{
This. file1.postedfile. saveas (utility. getserverpath (O. userid, filename, filetype, out resulturl, null ));
Window. doshowmodelessdialog (resulturl, "imgurl", true );
}
Else {
Window. Close ("the format of the file you uploaded is invalid. The correct format is SwF | GIF | BMP | JPEG | jpe | PNG ");
}

}




}

# Region: Obtain the client Control ID. The default value is imgurl.
Private string getclientcontrolid ()
{
String url = utility. url;
If (url = NULL | url = "")
Return "imgurl ";
If (URL. indexof ("? ") =-1)
Return "imgurl ";
Url = URL. Split (New char [] {'? '}) [1];
Return (url = "")? "Imgurl": URL. Trim ();
}
# Endregion
}

 

Corresponding class. CS

 

 

Public static void doshowmodelessdialog (string svalue, string textboxid, bool isclosecurrentpage)
{
String JS = @"
Function doshowmodelessdialog (svalue, textboxid ){
VaR imgurl = nvidialogarguments.doc ument. getelementbyid (textboxid );
If (typeof (imgurl) = 'object '){
Imgurl. value = svalue;
}
}";
JS + = "doshowmodelessdialog ('" + svalue + "', '" + textboxid + "');";
If (isclosecurerepage)
JS + = "window. Opener = NULL; window. Close ();";
Utility. Terminate (RegEx. Replace (JavaScript, "([// $] {1})", JS ));
}
}
}

 

Public static void terminate (string description)
{
Httpcontext. Current. response. Write (description );
Httpcontext. Current. response. End ();
}

 

 

# Region File Upload-obtain the physical path of the server
Public static string getserverpath (INT userid, string posted_filename, string posted_filetype, out string resulturl, string realfilename)
{
Resulturl = NULL;
If (posted_filename = NULL)
Return "";
If (posted_filename.lastindexof (".") =-1)
Return "";
If (posted_filename.indexof ("//") =-1)
Return "";
If (posted_filename.length <8)
Return "";
If (posted_filename.substring (1, 2 )! = "://")
Return "";
String [] arr = posted_filename.split (New char [] {'//'});

String filename = arr [arr. getupperbound (0)]. Trim (). tolower ();
String suffix = filename. Split (New char [] {'.'}) [1];
If (
Suffix = "SWF" |
Suffix = "GIF" |
Suffix = "jpg" |
Suffix = "BMP" |
Suffix = "Jpeg" |
Suffix = "jpe ")
{
Resulturl = "/uploadfiles /";
String filepath = system. Web. httpcontext. Current. server. mappath (resulturl );
Utility. createdirectory (filepath );
Filepath + = userid + "//";
Utility. createdirectory (filepath );

String filetype = "Images ";
If (suffix = "SWF ")
{
Filetype = "flashs ";

}
Filepath + = filetype + "//";
Utility. createdirectory (filepath );

If (realfilename! = NULL)
{
// If the source name of the uploaded file is not blank, use the source file name, which is generally used for batch upload.
Filepath + = realfilename;

Resulturl + = userid + "/" + filetype + "/" + realfilename;
Return filepath;
}
Else
{
String name = system. datetime. Now. ticks. tostring ();

Filepath + = Name + "." + suffix;

Resulturl + = userid + "/" + filetype + "/" + name + "." + suffix;
Return filepath;
}
}
Else
{
Return "";
}
}
# Endregion

 

 

# Region file directory-createdirectory
Public static void createdirectory (string folder)
{
If (Folder. indexof (":") =-1)
Folder = system. Web. httpcontext. Current. server. mappath (folder );
Try
{
If (! System. Io. Directory. exists (folder ))
{
System. Io. directoryinfo dir = system. Io. Directory. createdirectory (folder );
Dir = NULL;
}
}
Catch (exception ex)
{
Utility. Terminate ("Folder creation exception:" + ex. tostring ());
}
}
# Endregion

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.