JQuery uploadify Upload plugin appears HTTP Error 302 error resolution _jquery

Source: Internet
Author: User
Tags mkdir session id yii jquery file upload

Some time ago introduced the jquery uploadify upload plug-in use method, I encountered in the use of HTTP error 302 errors, there should be many people in the use of the encounter, this record down:

First of all, HTTP 302 is the meaning of the request being redirected, which is easy to understand if your uploadify processing upload script has session validation, this error occurs because Flash does not contain cookie information when it executes the POST request. and the server session will be based on the client's cookie to get SessionID. The session cannot be obtained without submitting cookies, and then the Uploadify returns a 302 (Request redirected) error.

The solution, of course, is to upload the session_id value to the server:

<script>
$ (document). Ready (function () { 
   $ (' #file_upload '). Uploadify ({ 
    ' uploader ': ' uploadify/ Uploadify.swf ', 
    ' script '  : ' uploadify.php ',
    ' folder '  : ' Uploads/file ', 
    ' formData ': {' Session ' : ' <?php echo session_id ();? > '}, 
    ' OnComplete ': function (event, ID, Fileobj, response, data) { 
     alert (response); 
    } 
   } 
); 

Then before server-side session validation:

if (Isset ($_post[' Session '))} { 
  session_id ($_post[' Session ')); 
  Session_Start ()//Note This function is to be session_id after the 

Of course, you can also pass the session ID directly in the URL.

The code in Yii is as follows:

$ (' #<?php echo $upload _name_id;? > '). uploadify ({' ButtonText ': ' Select File ... ', ' fileobjname ': ' Imgfile ', ' method ': ' Post ', ' Multi ': FA
      LSE, ' Queueid ': ' Filequeue ',/* ' uploadlimit ': 2,*/' filetypeexts ': ' *.gif;*.png;*.jpg;*.bmp;*.jpeg; ', ' Buttonimage ': ' <?php echo $this->_static_public?>/js/uploadify/select.png ', ' formData ': {' ses Sionid ': ' <?php echo Yii::app ()->session->sessionid;?> ', ' timestamp ': ' <?php echo time ();? > ', ' token ': ' <?php echo MD5 (' Unique_salt '. time ());?> ', ' modelname ': ' <?php echo $modelN Ame?> ', ' modelid ': ' <?php echo $model->id;?> '}, ' swf ': ' <?php echo $this->_stat Ic_public;?
      >/js/uploadify/uploadify.swf ', ' uploader ': ' <?php echo $this->createurl (' Uploadify/basicexecute ')?> ', ' Onuploadstart ': function () {$ (' #<?php echo $up _upload_name_id;?
 > img '). Remove ();       $ (' #<?php echo $up _upload_name_id;?
        > A '). Remove ();
        $imgHtml = '  '). Append ($imgHtml); 
        }, ' Onuploadsuccess ': function (file, data, response) {$ ('. Upload_load '). Remove (); 
        var json = $.parsejson (data); if (json.state = = ' Success ') {$ ("#<?php echo $d _upload_name_id;?
          > "). Remove ();
          $ (yt_upload_name_id). Val (Json.fileid); $imgHtml = ' <div id= ' <?php echo $d _upload_name_id;?          
          > ">";
          $imgHtml + + "<a href=" <?php echo $this->_baseurl?>/' + json.file + ' "target=" _blank ">"; $imgHtml + + "_baseurl?>/' +json.file+ ' "width=" "height=" and "align=" Absmiddle
          "/> ';
          $imgHtml + = ' </a> '; $imgHtml + = ' <a href= ' javascript:uploadifyremove ("' + Json.fileid + '", ";? PHP echo $d _upload_name_id;? > "," <?php echo $yt _upload_name_id;?
          > ")" > Delete </a> ';
          $imgHtml + = ' </div> '; $ (' #<?php echo $up _upload_name_id;?
        > '). Append ($imgHtml);
        else {alert (json.message);
      }, ' Onqueuecomplete ': function () {$ ('. Upload_load '). Remove ();  }
    });

Service side:

if (Isset ($_post[' sessionId ')) {
  $session = Yii::app ()->getsession ();
  $session->close ();
  $session->sessionid = $_post[' SessionID '];
  $session->open ();
}

Ps:jquery Upload plugin uploadify use Experience (summary)

Use your own instance:

1, JSP page:

<link href= "Jsp/js/jquery_upload/uploadify.css" rel= "stylesheet" type= "Text/css"/> <script "type=" text/ JavaScript "src=" Jsp/js/jquery-1.4.2.min.js "></script> <script type=" Text/javascript "src=" jsp/js/ Jquery_upload/swfobject.js "></script> <script type=" Text/javascript "src=" jsp/js/jquery_upload/ Jquery.uploadify.v2.1.4.min.js "></script>//jquery File Upload $ (document). Ready (function () {$ (" #uploadify "). u Ploadify ({' Uploader ': ' jsp/js/jquery_upload/uploadify.swf ', ' script ': ' Uploadfile.svl ', ' Cancelim
        G ': ' Jsp/js/jquery_upload/cancel.png ', ' Queueid ': ' Filequeue ', ' auto ': false, ' multi ': true, ' method ': ' POST ', ' scriptdata ': {' savefolder ': ' Stuphotos '},//get way to be effective ' fileext ': ' *.jpg;*.gif;*.png ',// Control upload file extension ' filedesc ': ' jpg, GIF, PNG file ',//control upload file extension description, both need to use ' buttonimg ': ' Jsp/js/jquery_upload/selec Tbtn.gif ', ' width ': 80,//' Browse ' button width ' oncomplete': function (event,id,fileobj,response,data) {//alert (response)//response for server response data},}); 
}); &LT;TD width= "class=" TabIndex style= "height:10px" > Photos:</td> <td> <input type= "file" Name= " Uploadify "id=" uploadify "/> <p> <a href=" javascript:$ (' #uploadify '). Uploadifyupload () "> Upload </a> 
| <a href= "javascript:$ (' #uploadify '). Uploadifyclearqueue ()" > Cancel upload </a> </p> <div id= "Filequeue" ></div> <input type= "hidden" name= "Stuphoto" id= "Stuphoto"/> </td>

2, server-side code

public class Uploadfileutil extends HttpServlet {private static final long serialversionuid = 1L; File Tmpdir = null;//The temporary storage directory of the uploaded file Savedir = null;//The Save directory after the uploaded file is public uploadfileutil () {super ();} protected V OID Doget (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException {doPost (
request, response);
  } protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { 
     try{if (servletfileupload.ismultipartcontent (Request)) {response.setcharacterencoding ("utf-8");/Be sure to prevent the return file name from being garbled Diskfileitemfactory DFF = new Diskfileitemfactory ();//Create the Object Dff.setrepository (tmpdir);//Specify the temporary directory of the uploaded file dff.se Tsizethreshold (1024000);//Specifies that the data size is cached in memory, in bytes servletfileupload SFU = new Servletfileupload (DFF);//Create the object sfu.se Tfilesizemax (5000000);//Specify the maximum size of a single upload file Sfu.setsizemax (10000000);//Specify the total size of multiple files uploaded at one time fileitemiterator FII = Sfu.getit Emiterator (request);//Resolve request requests,and returns the Fileitemiterator collection while (Fii.hasnext ()) {Fileitemstream FIS = Fii.next ();//get a file stream from the collection if (!FIS.ISFORMF Ield () && fis.getname (). Length () >0) {//filter out Form non-file field string filename = Fis.getname ();//get filename string E
       Xtname = "";
        if (Filename.lastindexof (".") >= 0) {extname = filename.substring (Filename.lastindexof (".")); Bufferedinputstream in = new Bufferedinputstream (Fis.openstream ());//Get file input stream String Uuidname = Uuid.randomuuid (). t Ostring (). ReplaceAll ("-", ""). toUpperCase ()//////////////////////////New Bufferedoutputstream (New F
      Ileoutputstream (New file (savedir+ "/" +uuidname+extname));/get file output stream Streams.copy (in, out, true);//start writing files to your designated upload folder
   }//jquery Upload method returns Response.getwriter (). Print ("Upload success");//Success}}catch (Exception e) {
  Response.getwriter (). Print ("Upload fail");//failure e.printstacktrace ();
} public void Init () throws Servletexception {Super.init ();  String serverpath = This.getservletconfig (). Getservletcontext (). Getrealpath ("/");//Get server path String Tmppath = Serverpat
   h+ "/tmpuploadsfolder/";
  String Savepath = serverpath+ "/uploadsfolder/";
  Tmpdir = new File (Tmppath);
  Savedir = new File (Savepath);
  if (!tmpdir.isdirectory ()) Tmpdir.mkdir ();
 if (!savedir.isdirectory ()) Savedir.mkdir (); }}

The above content is small to introduce you to the jquery uploadify upload plug-ins appear HTTP error 302 wrong solution, I hope you like.

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.