>  기사  >  웹 프론트엔드  >  jQuery Uploadify 업로드 플러그인_jquery의 Http 오류 302 오류에 대한 솔루션

jQuery Uploadify 업로드 플러그인_jquery의 Http 오류 302 오류에 대한 솔루션

WBOY
WBOY원래의
2016-05-16 15:26:092632검색

얼마 전에 jquery uploadify 업로드 플러그인 사용 방법을 소개했는데, 사용 중에 Http Error 302 오류 문제가 발생했을 것입니다. 여기에 기록하겠습니다.

우선 http 302는 요청이 리디렉션되었음을 의미하므로 이해하기 쉽습니다. 업로드 처리 업로드 스크립트에 세션 확인이 있는 경우 게시 요청을 실행할 때 플래시에 쿠키 정보가 포함되지 않기 때문에 이 오류가 발생합니다. , 서버 세션은 클라이언트 쿠키를 기반으로 SESSIONID를 가져옵니다. 당연히 쿠키를 제출하지 않으면 세션을 얻을 수 없으며 uploadify는 302(요청 리디렉션됨) 오류를 반환합니다.


물론 해결 방법은 session_id 값을 서버에 전달하는 것입니다.

<script>
$(document).ready(function() { 
   $('#file_upload').uploadify({ 
    'uploader' : 'uploadify/uploadify.swf', 
    'script'  : 'uploadify.php',
    'folder'  : 'uploads/file', 
    'formData': { 'session': '<&#63;php echo session_id();&#63;>'}, 
    'onComplete' : function(event, ID, fileObj, response, data) { 
     alert(response); 
    } 
   }); 
}); 
</script> 
그런 다음 서버 측 세션 확인 전:


if (isset($_POST['session'])){ 
  session_id($_POST['session']); 
  session_start();//注意此函数要在session_id之后 
} 
물론 URL에 세션 ID를 직접 전달할 수도 있습니다.


yii의 코드는 다음과 같습니다.


$('#<&#63;php echo $upload_name_id;&#63;>').uploadify({
      'buttonText': '选择文件..',
      'fileObjName': 'imgFile',
      'method': 'post',
      'multi': false,
      'queueID': 'fileQueue',
      /*'uploadLimit': 2,*/
      'fileTypeExts': '*.gif;*.png;*.jpg;*.bmp;*.jpeg;',
      'buttonImage': '<&#63;php echo $this->_static_public&#63;>/js/uploadify/select.png',
      'formData': {
        'sessionId'  : '<&#63;php echo Yii::app()->session->sessionID; &#63;>',
        'timestamp'  : '<&#63;php echo time();&#63;>',
        'token'    : '<&#63;php echo md5('unique_salt'.time()); &#63;>',
        'modelName' : '<&#63;php echo $modelName; &#63;>',
        'modelId' : '<&#63;php echo $model->id; &#63;>'
      },
      'swf': '<&#63;php echo $this->_static_public;&#63;>/js/uploadify/uploadify.swf',
      'uploader': '<&#63;php echo $this->createUrl('uploadify/basicExecute')&#63;>',
      'onUploadStart': function () {
        $('#<&#63;php echo $up_upload_name_id;&#63;> img').remove();
        $('#<&#63;php echo $up_upload_name_id;&#63;> a').remove();
        $imgHtml = '<img class="upload_load" src="static/images/upload.gif" align="absmiddle" />';
        $('#<&#63;php echo $up_upload_name_id;&#63;>').append($imgHtml);
      },  
      'onUploadSuccess': function(file, data, response) {
        $('.upload_load').remove(); 
        var json = $.parseJSON(data); 
        if (json.state == 'success') {
          $("#<&#63;php echo $d_upload_name_id;&#63;>").remove();
          $(yt_upload_name_id).val(json.fileId);
          $imgHtml ='<div id="<&#63;php echo $d_upload_name_id;&#63;>">';          
          $imgHtml += '<a href="<&#63;php echo $this->_baseUrl&#63;>/' + json.file + '" target="_blank">';
          $imgHtml += '<img src="<&#63;php echo $this->_baseUrl&#63;>/'+json.file+'" width="85" height="75" align="absmiddle"/>';
          $imgHtml += '</a>';
          $imgHtml += '<a href="javascript:uploadifyRemove("' + json.fileId + '","<&#63;php echo $d_upload_name_id;&#63;>","<&#63;php echo $yt_upload_name_id;&#63;>")">删除</a>';
          $imgHtml +='</div>';
          $('#<&#63;php echo $up_upload_name_id;&#63;>').append($imgHtml);
        } else {
          alert(json.message);
        }
      },
      'onQueueComplete':function () {
        $('.upload_load').remove();
      }
    }); 
서버:

if (isset($_POST['sessionId'])) {
  $session = Yii::app()->getSession();
  $session->close();
  $session->sessionID = $_POST['sessionId'];
  $session->open();
}

ps: jquery upload 플러그인 uploadify 사용 경험(요약)

직접 사용해 보세요:

1. jsp 페이지:

<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文件上传
$(document).ready(function()
    {
      $("#uploadify").uploadify({
        'uploader': 'jsp/js/jquery_upload/uploadify.swf',
        'script': 'uploadFile.svl',
        'cancelImg': 'jsp/js/jquery_upload/cancel.png',
        'queueID': 'fileQueue',
        'auto': false,
        'multi': true,
        'method':'POST',
        'scriptData':{'saveFolder':'stuPhotos'},//GET方式才可生效
        'fileExt' :'*.jpg;*.gif;*.png', //控制可上传文件的扩展名
        'fileDesc': 'jpg、gif、png文件', //控制可上传文件的扩展名描述,两者需要同时使用 
        'buttonImg':'jsp/js/jquery_upload/selectBtn.gif',
        'width':80,//"浏览"按钮宽度
        'onComplete':function(event,ID,fileObj,response,data){
         //alert(response) //response为服务器响应数据
        },
      });
}); 
<td width="200" class="tabIndex" style="height:10px">照片:</td>
<td>
<input type="file" name="uploadify" id="uploadify" />
<p>
<a href="javascript:$('#uploadify').uploadifyUpload()">上传</a>| 
<a href="javascript:$('#uploadify').uploadifyClearQueue()">取消上传</a>
</p>
<div id="fileQueue" ></div>
<input type="hidden" name="stuPhoto" id="stuPhoto" />
</td>

2. 서버 코드

public class UploadFileUtil extends HttpServlet {
private static final long serialVersionUID = 1L;
File tmpDir = null;// 初始化上传文件的临时存放目录
File saveDir = null;// 初始化上传文件后的保存目录
public UploadFileUtil() {
super();
}
protected void 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");//务必,防止返回文件名是乱码 
     DiskFileItemFactory dff = new DiskFileItemFactory();//创建该对象
     dff.setRepository(tmpDir);//指定上传文件的临时目录
     dff.setSizeThreshold(1024000);//指定在内存中缓存数据大小,单位为byte
     ServletFileUpload sfu = new ServletFileUpload(dff);//创建该对象
     sfu.setFileSizeMax(5000000);//指定单个上传文件的最大尺寸
     sfu.setSizeMax(10000000);//指定一次上传多个文件的总尺寸
     FileItemIterator fii = sfu.getItemIterator(request);//解析request 请求,并返回FileItemIterator集合
     while(fii.hasNext()){
      FileItemStream fis = fii.next();//从集合中获得一个文件流
      if(!fis.isFormField() && fis.getName().length()>0){//过滤掉表单中非文件域
       String fileName = fis.getName();//获取文件名
       String extName = "";
       if (fileName.lastIndexOf(".") >= 0) {
extName = fileName.substring(fileName.lastIndexOf("."));
}
        BufferedInputStream in = new BufferedInputStream(fis.openStream());//获得文件输入流
        String uuidName = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();//用UUID生成文件名
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(saveDir+"/"+uuidName+extName)));//获得文件输出流
        Streams.copy(in, out, true);//开始把文件写到你指定的上传文件夹
      }
     }
     //jquery上传方式返回
     response.getWriter().print("upload success");//成功
    }
  }catch(Exception e){
   response.getWriter().print("upload fail");//失败
    e.printStackTrace();
  }
 } public void init() throws ServletException {
  super.init();
  String serverPath = this.getServletConfig().getServletContext().getRealPath("/");//获取服务器路径
   String tmpPath = serverPath+"/tmpUploadsFolder/";
   String savePath = serverPath+"/uploadsFolder/";
  tmpDir = new File(tmpPath);
  saveDir = new File(savePath);
  if(!tmpDir.isDirectory())
    tmpDir.mkdir();
  if(!saveDir.isDirectory())
    saveDir.mkdir();
 }}
위 내용은 에디터에서 소개한 jQuery Uploadify 업로드 플러그인의 Http Error 302 오류에 대한 해결 방법입니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.