The use of Uploadify file upload component in asp.net

Source: Internet
Author: User

This control has a lot of parameter control, as well as event processing response, relatively easy to use. Parameter control can control the upload file multiple selection, file type, file size, number of files, check the existence of files, as well as some button parameters control, such as text, height, width, etc., for the successful submission of documents, complete operation, cancellation, stop upload, etc. have control, their help documents are also written more perfect, However, the method parameters for each version are completely different, but the control is a good control.

Control is first added to the prerequisite Script class library, because the control is leveraging jquery, you need to apply the jquery script file as shown below.

Jquery-1.8.0.min.js "
Jquerytools/uploadify/jquery.uploadify-3.1.min.js
Jquerytools/uploadify/uploadify.css

Configure some of the control's parameters, as well as the corresponding handling events, as shown below.

The code is as follows Copy Code


<script language= "javascript" type= "Text/javascript"
        $ (function () {
            var guid = ' <%=request[' Guid "]%> ';
            var type = ' <%=request[' type ']%> ';
            if (GUID = = NULL | | guid = = = "") {
   ;              GUID = NewGuid ();
           }
            if (type!= null) {
                 type = type + '/';
           }

$ (' #file_upload '). Uploadify ({


' swf ': ' uploadify.swf ',//flash file path


' ButtonText ': ' Browse ',//button text


' Uploader ': ' uploadhandler.ashx?guid= ' + GUID,//Processing ASHX page


' FormData ': {' folder ': ' Picture '},//pass parameter


' Queueid ': ' Filequeue ',//ID of the queue


' Queuesizelimit ': 10,//queue can upload the maximum number of files, the default is 999


' Auto ': false,//or automatically uploaded after file, default to True


' Multi ': true,//Is multiple-selected, the default is True


' removecompleted ': true,///remove sequence after completion, default to True


' Filesizelimit ': ' 10MB ',//single file size, 0 is unrestricted, acceptable KB,MB,GB and other units of string value


' Filetypedesc ': ' Image files ',//File description


' filetypeexts ': ' *.gif; *.jpg; *.png; *.bmp ',//uploaded file suffix filter


' Onqueuecomplete ': function (event, data) {//All queues after completion of events


Showupfiles (GUID, type, show_div);


Alert ("Upload complete!") ");


},


' Onuploaderror ': function (event, Queueid, Fileobj, errorobj) {


Alert (Errorobj.type + ":" + errorobj.info);


}


});


});

        function NewGuid () {
             var guid = "";
            for (var i = 1; I <= i++) {
   ;            var n = math.floor (Math.random () *16.0). ToString (16);
              GUID +=   N;
              if ((i==8) | | (i==12) | | (i==16) | | (I==20))
                GUID = = "-";
           }
            return GUID;
       }
    </script>

Again, this control should not refer to other instructions on the web, otherwise the parameters and usage may not be correct, be sure to find the corresponding version of the description (this article refers to 3.1.1), it is best to refer to the version of the online documentation.

The above parameters, I basically gave comments, there are not very important parameters, not listed here, you need to refer to the online documentation.

It is worth mentioning that this version can modify the text inside the flash, very good, very annoying to the previous default browse English, although the previous alternative to the image can be modified text, but still not very useful. This directly modifies the text, very good.

It is worth noting that the uploader parameter, this is our ASHX background processing program, is the control to submit files to the page to save processing, add database records and other operations.

The page code is simple to use, as shown below

The code is as follows Copy Code

<body style= "margin-left:10px; margin-top:10px ">
<form id= "Form1" runat= "Server" enctype= "Multipart/form-data" >
<div id= "Filequeue" class= "Filequeue" ></div>

    <div>
    <input type= "file" Name= "File_upload" id= "File_upload"/
        <p>
             <input type= "button" class= "Shortbutton" id= "Btnupload" onclick= "javascript:$" (' #file_ Upload '). Uploadify (' upload ', ' * ') "value=" Upload "/>
             &nbsp;&nbsp;&nbsp;&nbsp;
            <input type= button "class=" Shortbutton "Id=" Btncancelupload "onclick=" javascript:$ (' #file_upload '). Uploadify (' Cancel ') ' value= ' Cancel '/>
         </p>
        <div id= "Div_show_ Files "></div>
    </div>
    </form>
</body>

The key is the background upload file save operation, asp.net generally adopt ashx processing page to deal with.

The code is as follows Copy Code

<summary>
File Upload Background Processing page
</summary>
[WebService (Namespace = "http://tempuri.org/")]
[WebServiceBinding (ConformsTo = wsiprofiles.basicprofile1_1)]
public class Uploadhandler:ihttphandler
{
public void ProcessRequest (HttpContext context)
{
Context. Response.ContentType = "Text/plain";
Context. Response.Charset = "Utf-8";

Try
{
String guid = context. Request.querystring["GUID"];
String folder = Context. request["folder"];
Logtexthelper.info (folder);

Httppostedfile file = context. request.files["Filedata"];


if (file!= null)


{


String oldfilename = file. filename;//Original filename


int size = file. contentlength;//Attachment Size





String extenstion = Oldfilename.substring (Oldfilename.lastindexof (".") + 1);/suffix name


String newfilename = Getnewfilename (oldfilename);//Generate New file name


Logtexthelper.info (NewFileName);

Upload the #region to the remote server


Fileservermanage FSW = new Fileservermanage ();


String uploadfilepath = "/" + NewFileName;


if (!string. IsNullOrEmpty (folder))


//{


Uploadfilepath = string. Format ("/{0}/{1}", folder, NewFileName);


//}


bool uploaded = FSW. UploadFile (file. InputStream, "/" + folder + "/" + NewFileName);


#endregion

#region Local server Upload

AppConfig config = new AppConfig ();


string uploadfiles = config. Appconfigget ("Uploadfiles");


if (string. IsNullOrEmpty (Uploadfiles))


{


Uploadfiles = "Uploadfiles";


}


if (!string. IsNullOrEmpty (folder))


{


Uploadfiles = Path.Combine (uploadfiles, folder);


}

String uploadpath = Path.Combine (HttpContext.Current.Server.MapPath ("/"), uploadfiles);


if (! Directory.Exists (Uploadpath))


{


Directory.CreateDirectory (Uploadpath);


}


String newfilepath = Path.Combine (Uploadpath, NewFileName);


Logtexthelper.info (Newfilepath);


File. SaveAs (Newfilepath);


bool uploaded = File.exists (Newfilepath);

#endregion

if (uploaded)


{


Database records written to an attachment after a successful save #region file


Attachmentinfo attachmentinfo = new Attachmentinfo ();


Attachmentinfo.editortime = DateTime.Now;


Attachmentinfo.fileextend = extenstion;


Attachmentinfo.filename = Folader + "/" + NewFileName;


Attachmentinfo.oldfilename = Oldfilename;


Attachmentinfo.size = Size;


Attachmentinfo.guid = Guid;


Bllfactory&lt;attachment&gt;. Instance.insert (Attachmentinfo);


#endregion


}


}


Else


{


Logtexthelper.error ("Upload file failed");


}


}


catch (Exception ex)


{


Logtexthelper.error ("Upload file Failed", ex);


Throw


}


}

<summary>
Get a new name for example: Aa.jpg into AA (20090504). jpg
</summary>
<param name= "FileName" > File name [aa.jpg]</param>
<returns> New file name </returns>
public static string Getnewfilename (String fileName)
{
if (string. IsNullOrEmpty (FileName))
return string. Empty;

           //File suffix name
             string extenstion = Filename.substring (Filename.lastindexof (".") + 1);
            String name = filename.substring (0, Filename.lastindexof (".")) + "(" + DateTime.Now.ToFileTime () + ")";
            String newfilename = name + "." + extenstion;
            return newfilename;
       }

public bool IsReusable
{
Get
{
return false;
}
}
}

Perform an example upload operation, we will be prompted to upload the successful operation, the corresponding directory, there will be the corresponding file written.

These are the instructions for using the batch upload file control uploadify

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.