2011-08-21 3 views
1

XMLHttpRequest를 사용하여 파일을 서버에 업로드하려고합니다. 여기에 내가 코드가 수행하고자하는 단계는 다음과 같습니다업로드 된 파일 목록을 변경하려면 어떻게해야합니까?

  1. 목록 파일 목록 UL
  2. 파일 (들)을 업로드에서 파일 동안 파일이 완전히 업로드되면 진행 표시 줄
  3. 를 표시 해당 파일의 목록 항목을 진행 막대가없는 링크로 변경하십시오. 이것은 내가 문제가있는 곳입니다. 여기
    <h1>Upload Files</h1> 
    <input type='file' name='doc_upload_field[][]' multiple='multiple' id='doc_upload_field' /> 
    <ul id='filelist'></ul> 
    

    내가 함께 일하고 자바 스크립트 코드입니다 : 여기

내가 작업하고있는 HTML 코드입니다

function transferFailed(evt) { 
    alert("An error occurred while transferring the file."); 
}      
function transferCanceled(evt) { 
    alert("The transfer has been canceled by the user."); 
} 

var filelist = $('#filelist');//define where the list of files will go 
var url = "/"; 

function handleFileSelect_inputfield(evt) { 
    var files = evt.target.files; // FileList object 


    // run through each file individually. 
    for (var i = 0, f; f = files[i]; i++) {  

    var li = $("<li><strong>" + f.name + "</strong> (" + f.type +") - " + f.size + " bytes <div class='progress_bar'><div class='percent'>&nbsp;</div></div></li>"); 
    filelist.append(li);//put the file in the filelist 

    var formData = new FormData(); 
    formData.append(f.name, f); 

    //upload through xmlhttprequest 
    var xhr = new XMLHttpRequest();   
    xhr.upload.li = li; 
    xhr.upload.addEventListener("progress", function(e) { 
    if (e.lengthComputable) { 
     var percentLoaded = Math.round((e.loaded/e.total) * 100);      
     // Increase the progress bar length. 
     if (percentLoaded < 100) { 
     this.li.find(".progress_bar").addClass('loading'); 
     this.li.find(".percent").width(percentLoaded + '%'); 
     } 
    }    
    }, false); 
    xhr.upload.addEventListener("load", function(e) { 
    //uploading is complete     
    }, false);   

    xhr.upload.addEventListener("error", transferFailed, false); 
    xhr.upload.addEventListener("abort", transferCanceled, false); 

    xhr.open('POST', url, true); 
    xhr.responseType = 'text'; 
    xhr.onload = function(e) {     
    if (this.readyState==4){ 
     if (this.status == 200) { 
      //console.log(this.response); 
      console.log("finished=" + li);//returns as an object 
      //console.log("filename=" + f.name);//error: cannot read property 'name' of undefined    
      //change the list item. Not working... 
      this.li.find("li").html("<a href='#'>" + f.name + "</a>");      
     } 
    } 
    };          
    xhr.send(formData); // multipart/form-data      
    }  
} 

document.getElementById('doc_upload_field').addEventListener('change', handleFileSelect_inputfield, false); 

모든 것이 작동하는 것 같군,하지만 난 할 때 목록 항목을 변경하려면 li, 인식하지 못합니다. 나는 호출하여 진행률 표시 줄의 길이를 변경할 수 있어요 :

this.li.find(".progress_bar").addClass('loading'); 
this.li.find(".percent").width(percentLoaded + '%'); 

을하지만 목록 항목을 변경하고자 할 때 :

this.li.find("li").html("<a href='#'>" + f.name + "</a>"); 

이 작동하지 않습니다.

진행률 표시 줄을 변경할 때 누가 그것을 찾을 수 있지만 업로드 한 후에는 찾지 않는 이유를 아는 사람이 있습니까?

답변

0

this.li.find("li") 

는 소자 <li><li> 다른 요소 내부 을 찾는 식. 아무도 없기 때문에 아무 일도 일어나지 않습니다.

난 그냥

this.li.html("<a href='#'>" + f.name + "</a>"); 

당신이 원하는 것을해야한다고 생각합니다. 아니면 그냥이 작업을 수행 할 수 있습니다 : 당신은 이미 DOM에 붙어했기 때문에

this.li = $("<li><a href='#'>" + f.name + "</a></li>"); 

편집을 죄송 없음이 작동하지 않습니다. 하지만 첫 번째 작업을해야합니다.

편집 — 당신은 클로저 관련 문제 (또는 범위 관련 문제)가 있습니다. 당신이 할 수있는 일은 이미 "li"값에 대해했던 것과 같습니다. 이에 "xhr.upload"또 다른 속성을 추가

xhr.upload.updated_li = "<a href='#'>" + f.name + "</a>"; 

는 "xhr.updated.li"로 설정 그 권리를 수행합니다. 그런 다음 이벤트 처리기에서 수행 할 수있는 작업은 다음과 같습니다.

this.li.html(this.updated_li); 
+0

답장을 보내 주셔서 감사합니다. 나는 처음 시도했지만 효과가 없었다. 오류는 "정의되지 않은"html '메서드를 호출 할 수 없습니다. 편집 : 그것을 다시 시도하고 그것은 .... 감사합니다. – Jason

+0

내가 f를 넣을 때.그것은 작동하지 않는 링크의 이름, 오류가 나타납니다 "밖으로 정의되지 않은 속성 '이름'읽을 수 없습니다"오류가 발생하지 않습니다. – Jason

+0

오 오 잘 당신은 폐쇄 관련 문제가 있습니다; 나는'for' 루프를 알아 채지 못했습니다. 잠시만 기다려주세요. 답변을 업데이트하겠습니다. – Pointy

관련 문제