Uploadify's asp. NET Image upload and processing solution for session loss

Source: Internet
Author: User
Tags auth documentation file upload httpcontext session id php tutorial rar wrapper

Plug-in asp tutorial.. net is an application instance on the website. I hope it will be helpful to you. I hope you can point out and forgive me for anything wrong with it (this is the debut in the next technical blog ). Well, the following describes how to use the plug-in.

<Title> uploadify -- example </title>
 
<Script type = "text/Web effects" src = "uploader/jquery-1.4.1.min.js" kesrc = "uploader/jquery-1.4.1.min.js"> </script>
 
<Script type = "text/javascript" src = "uploader/jquery. uploadify. v2.1.0.min. js" kesrc = "uploader/jquery. uploadify. v2.1.0.min. js"> </script>
 
<Script type = "text/javascript" src = "uploader/swfobject. js" kesrc = "uploader/swfobject. js"> </script>
 
<Link type = "text/css tutorial" href = "uploader/uploadify.css" kesrc = "uploader/uploadify.css" rel = "stylesheet">
<Style type = "text/css">
. Wrapper {width: 400px; margin: 10px auto}
</Style>
 
<Form id = "form1" runat = "server">
<Div class = "wrapper">
<B> uploadify sample program </B>
<Div id = "fileinput1">
</Div>
<A href = "javascript: $ ('# fileinput1 '). uploadifyupload () "kesrc =" javascript: $ ('# fileinput1 '). uploadifyupload () "> Upload </a> | <a href =" javascript: $ ('# fileinput1 '). uploadifyclearqueue () "kesrc =" javascript: $ ('# fileinput1 '). uploadifyclearqueue () ">
Cancel Upload </a>
</Div>
 
<Script type = "text/javascript">
$ ("# Fileinput1"). uploadify ({
'Upload': 'uploader/uploadify.swf ',
'Method': 'GET ',
'Script': 'uploadfile. aspx ',
'Cancelimg': 'uploader/cancel.png ',
'Auto': false,
'Multi ': true,
});
</Script>
 
</Form>

Flash, so we use swfobject. js to process flash. swfobject is an independent and agile javascript module used to insert adobe flash Media Resources (*. swf files) in html. The javascript script in this module can automatically detect the support of flash plug-ins by mainstream browsers on PCs and mac machines. It makes inserting flash media resources as simple and secure as possible. In addition, it is very consistent with the search engine optimization principles. In addition, it can avoid non-standard tags such as object and embed in your html and xhtml, so as to conform to more standards.

 

Public partial class uploadfile: system. web. ui. page
{
Protected void page_load (object sender, eventargs e)
    {
Try
        {
// Obtain the uploaded file data
Httppostedfile file = request. files ["filedata"];
String filename = file. filename;
// The filename retrieved by different browsers is different (some are absolute paths and some are only file names), so processing is required.
If (filename. indexof ('')>-1)
            {
Filename = filename. substring (filename. lastindexof ('') + 1 );
            }
Else if (filename. indexof ('/')>-1)
            {
Filename = filename. substring (filename. lastindexof ('/') + 1 );
            }
// Upload Directory
String uploaddir = "~ /Files /";
// Upload path
String uploadpath = uploaddir + guid. newguid () + filename;
// Save the file
File. saveas (server. mappath (uploadpath ));
// If the following code is missing, the display of the upload queue will not disappear automatically after the upload is successful.
Response. write ("1 ");
        }
Catch
        {
Response. write ("0 ");
        }
    }
}

In general, for example, uploadify and swfupload use flash clients. In this way, the useragent generated by these clients is different from the user-agent used by the browser. Therefore, although a user logs on to your system and generates a session, another session is generated when the upload program is triggered (when the preceding useragent option is enabled ). Therefore, ci creates another session for uploadify when you upload a file instead of losing the session. Now that we can find the root cause of the problem, we can try to let the server manually pass the session value before the session is null.

The solution in the asp.net tutorial is as follows:

Add the following code to the uploaded page:

Var auth = "<% = request. cookies [formsauthentication. formscookiename] = null? String. empty: request. cookies [formsauthentication. formscookiename]. value %> ";
Var asps tutorial essid = "<% = session. sessionid %> ";

Then the code of the initialization plug-in is changed to the following form:

$ ("# Fileinput1"). uploadify ({
'Upload': '/scripts/uploader/uploadify.swf ',
'Method': 'GET ',
'Script': '/mystudio/gouploadavatar ',
'Cancelimg': '/scripts/uploader/cancel.png ',
'Sizelimmit ': 2048000,
'Multi ': false,
'Filedesc': 'Select jpg, png, gif ',
'Fileext ':' *. jpg; *. png; *. gif ',
 
'Oncomplete': function (e, queueid, fileobj, response, data ){
 
},
'Onselectonce ': function (e, data ){
$ ('# Fileinput1'). uploadifysettings ('scriptdata', {'aspsessid': aspsessid, 'authid': auth });
            }
});

Note that the above sentence is critical.

$ ('# Fileinput1'). uploadifysettings ('scriptdata', {'aspsessid': aspsessid, 'authid': auth });

Next, we must forcibly assign the passed sessonid to the cookies of the current request before the server session is empty and created, so that the server will think that the original session is passed over. The following code can be added to the global. asax file:

Protected void application_beginrequest (object sender, eventargs e)
        {
/* We guess at this point session is not already retrieved by application so we recreate cookie with the session id ...*/
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
            {
            }

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
            {
            }
        }

Private void updatecookie (string cookie_name, string cookie_value)
        {
Httpcookie cookie = httpcontext. current. request. cookies. get (cookie_name );
If (null = cookie)
            {
Cookie = new httpcookie (cookie_name );
            }
Cookie. value = cookie_value;
Httpcontext. current. request. cookies. set (cookie );
        }

At this time, when you access the page of the file to be uploaded, the error "the session status has already created a session id, but the response has been refreshed by the application and cannot be saved" may be reported, you can. the config file changes the session storage method. Generally, it is stored in "inproc" by default. We change it to the stateserver mode, that is, in the system. add under a web node

<Sessionstate mode = "stateserver" stateconnectionstring = "tcpip = 127.0.0.1: 42424" timeout = "30"> </sessionstate>

OK, the problem is solved, although it seems troublesome to solve this problem (I don't know how to solve it on other websites, at least in. but such a good file Upload plug-in is worth doing.

 


The jquery + flash-based multi-file Upload plug-in uploadify is available at http://www.uploadify.com/demos/shao.


How is it? It works well. It supports multi-file upload and progress prompts, which gives users a great experience. It is also an open-source project, you can freely use and modify your project.
Project home address: http://www.uploadify.com/plug-in demo address: http://www.uploadify.com/demos/
Plug-In download address: http://www.uploadify.com/download/ plug-in user documentation: http://www.uploadify.com/documentation/


Okay. About some common parameters.

Uploader: The relative path of the uploadify.swf file. This swf file is a button with a text browse. After clicking it, it fades out the open file dialog box. Default value: uploadify.swf.
Script: The relative path of the background processing program. Default value: uploadify. php Tutorial
Checkscript: used to determine whether the selected file to be uploaded is in the relative path of the background processing program on the server
Filedataname: Set a name based on the name in the server handler to obtain the data of the uploaded file. The default value is filedata.
Method: The default submission method is post or get.
Scriptaccess: the access mode of the flash script file. If you set it to always in a local test, the default value is samedomain.
Folder: directory where the uploaded files are stored.
Queueid: id of the file queue, which is consistent with the id of the div storing the file queue.
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 file selection box is displayed as follows:
Fileext: Set the file type that can be selected. The format is '*. doc; *. pdf; *. rar '.
Sizelimit: specifies the size limit of the file to be uploaded.
Simuploadlimit: the number of simultaneous uploads allowed. Default value: 1.
Buttontext: the text of the browser button. Default value: browse.
Buttonimg: Path of the image of the browser button.
Hidebutton: if it 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, the result is reversed when you move the cursor over the Browse button.
Width: set the width of the browser button. Default value: 110.
Height: set the height of the Browse button. Default value: 30.
Wmode: If this parameter is set to transparent, the flash background file of the browser button is transparent, and the flash file is 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.

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.
Onselectonce: triggered when a single file or multiple files are uploaded. 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: 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 same as the three parameters in onselect. The 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, which correspond to two parameters in oncancel.

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

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.