Errors such as jquery. uploadify Asp.net (C #) file, Multifile upload plug-in, and session failure

Source: Internet
Author: User
ArticleDirectory
    • Add the following code to application_beginrequest of Global. asax:

Uploadify is an upload plug-in of jquery that displays progress and supports Multifile upload. However, for official instances

The only drawback of uploadify is that it does not support Chinese buttons.

Download official documentation official demo

Implementation

Uploadify has the following minimum requirements:

  • Jquery 1.4.x or greater
  • Swfobject 2.2 or greater
  • Flash Player 9.0.24 or greater

    Required files

  • Cancel.png
  • Jquery. uploadify. v2.1.4.min. js
  • Jquery-1.4.2.min.js
  • Swfobject. js
  • Uploadify.css
  • Uploadify. php
  • Uploadify.swf

    BasicCode

         

    * Make Sure You Have The write permission for the uploaded folder.

     
    <Input type = "file" name = "uploadify" id = "uploadify"/> <a href = "javascript: $ ('# uploadify '). uploadifyupload () "> upload </a> | <a href =" javascript: $ ('# uploadify '). uploadifyclearqueue () "> cancel upload </a>
    Main Parameters

    Example:

    $ (Document ). ready (function () {$ ('# fileinput1 '). fileupload ({'upload': 'uploader.swf ', // not much about 'script':'/ajaxbyjquery/file. do ', // Process Action 'cancelim': 'cancel.png', 'folder': '', // The default storage path of the server is 'scriptdata': {'methed': 'uploadfile ', 'arg1', 'value1'}, // pass the parameter to the background. methed, arg1 is the parameter name, uploadfile, and value1 is the corresponding parameter value, the server uses request ["arg1"] 'buttontext': 'uploadfile', // the button to display text. Chinese characters are not supported. For the solution, see // 'buttonimg ': 'image path', // solve the Chinese problem by setting the background image, which is to make the background image look like a button 'multi ': 'true', // Multifile upload switch 'fileext ': '*. XLS ;*. CSV ', // file filter 'filedesc': '.xls', // For details about file filter, see 'oncomplete': function (event, queueid, file, serverdata, data) {// serverdata is the string value returned by the server. Alert (serverdata );}});});
     
    Scriptdata
    Pass parameters to the backend. methed, arg1 is the parameter name, uploadfile, and value1 is the corresponding parameter value. The server uses request. getp
     
    Serverdata in oncomplete
    Value returned from the background to the foreground
     
    Optional Parameter

    The parameters of the uploadify function are in JSON format. You can modify the key value of the JSON object to customize the settings. For example, if multi is set to true or false, you can control whether multi-File Upload can be performed, the following describes the meanings of these key values:

    Uploader: Relative path of the uploadify.swf file. The SWF file is a button with a text browse. After clicking it, it fades out and opens the file dialog box. Default Value: uploadify.swf.

    Script: Background processingProgram. Default Value: uploadify. php

    Checkscript: Used to determine the relative path of the background processing program for uploading the selected file on the server

    Filedataname: Set a name to retrieve the data of the uploaded file in the server handler. The default value is filedata.

    Method: The default submission mode is post or get.

    Scriptaccess:The access mode of the flash script file. If it is set to always in a local test, the default value is samedomain.
    Folder:The directory where the uploaded files are stored.

    Queueid:The ID of the file queue, which is consistent with the ID of the DIV that stores the file queue. Position of the progress bar

  • Queuesizelimit:When multiple files are allowed to be generated, set the number of selected files. Default Value: 999.

    Multi:When set to true, multiple files can be uploaded.

    Auto:Set to true. When a file is selected, it is uploaded directly. If it is set to false, You need to click the upload button to upload the file.

    Filedesc:This attribute value is valid only after the fileext attribute is set. It is used to set the prompt text in the Select File Dialog Box. For example, if filedesc is set to "select RAR Doc PDF file", the effect of opening the file selection box is as follows:

    Fileext:Set the file type that can be selected, in the format of '*. Doc; *. pdf; *. rar '.

    Sizelimit:The size limit of the uploaded file.

    Simuploadlimit:The default value is 1.

    Buttontext:The text of the Browse button. Default Value: browse.

    Buttonimg:The path of the Browse button.

    Hidebutton:If this parameter is set to true, the image of the Browse button is hidden.

    Rolover:The values are true and false. If it is set to true, a reverse effect is displayed when you move the cursor over the Browse button.

    Width:Set the browser button width. Default Value: 110.

    Height:Set the height of the Browse button. Default Value: 30.

    Wmode:Setting this parameter to transparent can make the flash background file of the browser button transparent, and the flash file will be set to the top level of the page. Default Value: opaque.

    Cancelimg: Select the close button icon for each file after the file is in the file queue, for example:

    The value of the key value described above is a string or boolean type, which is relatively simple. The value of the key value to be introduced is a function, you can return some information to the user when selecting files, errors, or other operations.

    Oninit:Perform initialization..

    Onselect:Triggered when a file is selected. This function has three parameters.

  • Event: event object.
  • Queueid: the unique identifier of a file. It consists of 6 random characters.
  • Fileobj: Selected file object, which has five attributes: name, size, creationdate, modificationdate, and type.
    $ (Document ). ready (function () {$ ("# uploadify "). uploadify ({'uploader': 'js/jquery. uploadify-v2.1.0/uploadify.swf ', 'script': 'uploadhandler. ashx', 'canonicalmg ': 'js/jquery. uploadify-v2.1.0/cancel.png ', 'folder': 'uploadfile', 'queueid': 'filequeue', 'auto': false, 'Multi ': True, 'oninit': function () {alert ("1") ;}, 'onselect': function (E, queueid, fileobj) {alert ("unique identifier: "+ queueid +" \ r \ n "+" file name: "+ fileobj. name + "\ r \ n" + "file size:" + fileobj. size + "\ r \ n" + "creation time:" + fileobj. creationdate + "\ r \ n" + "last modification time:" + fileobj. modificationdate + "\ r \ n" + "file type:" + fileobj. type );}});});

     

    Onselectonce: Triggered when a single file or multiple files are uploaded and selected. This function has two parameters, event, and data, which have the following attributes:

  • Filecount: Total number of selected files.
  • Filesselected: select the number of files at the same time. If three files are selected at a time, the attribute value is 3.
  • Filesreplaced: If two files a and B exist in the file queue, select a and B again when selecting the file again. The attribute value is 2.
  • Allbytestotal: total size of all selected files.

    Oncancel:This is triggered when you click the close button of a file in the file queue or click Cancel upload. This function has four parameters: event, queueid, fileobj, and data. The first three parameters are the sameOnselectThe data object has two attributes: filecount and allbytestotal.

  • Filecount: number of remaining files in the file queue after a file is canceled.
  • Allbytestotal: the size of the remaining files in the file queue after a file is canceled.

    Onclearqueue :Triggered when the fileuploadclearqueue function is called. There are two parameters: Event and data.OncancelTwo corresponding parameters in.

    Onqueuefull:Triggered when queuesizelimit is set and the number of selected files exceeds the value of queuesizelimit. This function has two parameters: Event and queuesizelimit.

    Onerror:Triggered when an error occurs during the upload process. This function has four parameters: event, queueid, fileobj, and errobj. The first three parameters are the same as above. The errobj object has two attributes: type and info.

  • Type: indicates the type of the Error. There are three types: 'http', 'io', or 'security'
  • Info: Error description

    Onopen:Trigger upon clicking upload. If auto is set to true, It is triggered when a file is selected. If multiple files are uploaded, the entire file queue is traversed. This function has three parameters: event, queueid, and fileobj. The parameters are interpreted as the same as above.

    Onprogress: Triggered when you Click Upload. If auto is set to true, It is triggered when you select a file. If multiple files are uploaded, the entire file queue is traversed and triggered after onopen. This function has four parameters: event, queueid, fileobj, and data. The first three parameters are interpreted as the same as above. Data Objects have four attributes: percentage, bytesloaded, allbytesloaded, and speed:

  • Percentage: percentage of current completions
  • Bytesloaded: Current upload size
  • Allbytesloaded: size of the uploaded file queue
  • Speed: the upload speed is kb/s.

    Oncomplete: Triggered after the file is uploaded. This function has four parameters: event, queueid, fileobj, response, and data. The first three parameters are the same as above. Response is the value returned by the background processing program. In the preceding example, response is 1 or 0. Data has two attributes: filecount and speed.

  • Filecount: the number of files that have not been uploaded.
  • Speed: Average File Upload rate kb/s
    $ ('# File_upload '). uploadify ({'upload': '/uploadify/uploadify.swf', 'script': '/uploadify. PHP ', 'canonicalimg':'/uploadify/cancel.png ', 'folder':'/uploads', 'data': True, 'oncomplete': function (event, ID, fileobj, response, data) {alert ('there are '+ data. filecount + 'files remaining in the queue. ');}});

    Note: The fileobj object is not the same as the above mentioned. The fileobj object of oncomplete has a filepath attribute to retrieve the path of the uploaded file.

    Onallcomplete:Triggered when all files in the file queue are uploaded. This function has two parameters: Event and data. Data has four attributes:

  • Filesuploaded: Number of all uploaded files.
  • Errors: number of errors.
  • Allbytesloaded: total size of all uploaded files.
  • Speed: Average upload speed kb/s
    $ ('# File_upload '). uploadify ({'upload': '/uploadify/uploadify.swf', 'script': '/uploadify. PHP ', 'canonicalimg':'/uploadify/cancel.png ', 'folder':'/uploads', 'onallcomplete': function (event, data) {alert (data. filesuploaded + 'files uploaded successfully! ');}});

    In the preceding example, the uploadifyupload and uploadifyclearqueue functions are used. In addition, there are several functions:

    Uploadifysettings: You can dynamically modify the key values described above, as shown in the following code:

     
    $ ('# Uploadify'). uploadifysettings ('folder', 'js ');

    If the upload button event is written as follows, the file will be uploaded to the directory defined by uploadifysettings.

     
    <A href = "javascript: $ ('# uploadify'). uploadifysettings ('folder', 'js ');
     
    $ ('# Uploadify'). uploadifyupload () "> upload </a>

    Uploadifycancel:This function accepts a queueid as the parameter. You can cancel the file specified by queueid in the file queue.

    $ ('# Uploadify'). uploadifycancel (ID );
     
     
    Common Errors: 1. The file size is too large.
     
     
     
    <Configuration> <system. Web>  
    2. The session cannot be obtained.

    Flash sends the cookie of the current page to upload. ashx in IE, but does not send the cookie of the current page to upload. ashx in chrome or Firefox. Because the session is implemented by the sessionid stored in the cookie (the ASP. the net video tutorial describes the relationship between sessions and cookies. If you are not familiar with this, refer to "Chuan Zhi podcast video tutorial version 2011: Asp. net, so that the current page cookie will not be passed to the Flash Request Upload. ashx, so the requested file is sent to upload. ashx is a new session. Of course, this session is not logged on.

    The idea for solving this problem is also very simple, that is, manually passing the sessionid to the server, then the server reads the sessionid and loads the session.
  • Add the following code to application_beginrequest of Global. asax:
  • # Region Upload Component void application_beginrequest (Object sender, eventargs e) {// resume the session value of the flash Upload Component // 'scriptdata': {'aspsessid ':' <% = session. sessionid %> '} Try {string session_param_name = "aspsessid"; string session_cookie_name = "ASP. net_sessionid "; if (httpcontext. current. request. form [session_param_name]! = NULL) {updatecookie (session_cookie_name, httpcontext. Current. Request. Form [session_param_name]);} else if (httpcontext. Current. Request. querystring [session_param_name]! = NULL) {updatecookie (session_cookie_name, httpcontext. current. request. querystring [session_param_name]);} catch (exception ex) {// response. statuscode = 500; // response. write ("error initializing session");} // If the website still uses the formsauthentication verification of membership, then you also need to process the authid according to the sessionid method // 'scriptdata': {"aspsessid": "<% = session. sessionid %> "," authid ":" <% = request. cookies [formsauthentication. formsco Okiename]. Value %> "} Try {string auth_param_name =" authid "; string auth_cookie_name = formsauthentication. formscookiename; If (httpcontext. Current. Request. Form [auth_param_name]! = NULL) {updatecookie (auth_cookie_name, httpcontext. Current. Request. Form [auth_param_name]);} else if (httpcontext. Current. Request. querystring [auth_param_name]! = NULL) {updatecookie (auth_cookie_name, httpcontext. current. request. querystring [auth_param_name]);} catch (exception ex) {// response. statuscode = 500; // response. write ("error initializing Forms authentication") ;}} void updatecookie (string cookie_name, string cookie_value) {httpcookie cookie = httpcontext. current. request. cookies. get (cookie_name); If (cookie = NULL) {cookie = new httpcookie (cookie_name); httpcontext. current. request. cookies. add (cookie);} cookie. value = cookie_value; httpcontext. current. request. cookies. set (cookie) ;}# endregion

  • Backend receiving code
    Public void processrequest (httpcontext context) {context. response. contenttype = "text/plain"; context. response. charset = "UTF-8"; httppostedfile file = context. request. files ["filedata"]; string uploadpath = httpcontext. current. server. mappath (@ context. request ["folder"]) + "\"; if (file! = NULL) {If (! Directory. exists (uploadpath) {directory. createdirectory (uploadpath);} file. saveas (uploadpath + file. filename); // if the following code is missing, the context will not automatically disappear after the upload queue is successfully displayed. response. write ("Upload successful! ") ;}Else {context. response. Write (" 0 ");}}

    Download source code: uploadify.zip

  • 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.