大文件上传导致浏览器挂起

时间:2011-09-23 15:57:06

标签: javascript xmlhttprequest

小文件流畅,即使同时上传100个5兆字节文件(虽然它一次只能处理5个文件,其余部分排队)但是150MB文件会导致浏览器在启动时挂起几秒钟。 / p>

  function start(file) {
    var xhr = new XMLHttpRequest();
    ++count;

    var container = document.createElement("tr");

    var line = document.createElement("td");
    container.appendChild(line);
    line.textContent = count + ".";

    var filename = document.createElement("td");
    container.appendChild(filename);
    filename.textContent = file.fileName;
    filename.className = "filename";

    initXHREventTarget(xhr.upload, container);

    var tbody = document.getElementById('tbody');
    tbody.appendChild(container);
    tbody.style.display = "";

    var boundary = "xxxxxxxxx";

    xhr.open("POST", "uploader.php");

    xhr.setRequestHeader("Content-Type", "multipart/form-data, boundary="+boundary); // simulate a file MIME POST request.  
    xhr.setRequestHeader("Content-Length", file.size); 

    xhr.onreadystatechange = function() {  
        if (xhr.readyState == 4) {
            if ((xhr.status >= 200 && xhr.status <= 200) || xhr.status == 304) {
                if (xhr.responseText != "") {  
                    alert(xhr.responseText); // display response.  
                }  
            }  
        } 
    }

    var body = "--" + boundary + "\r\n";  
    body += "Content-Disposition: form-data; name='upload'; filename='" + file.fileName + "'\r\n";  
    body += "Content-Type: application/octet-stream\r\n\r\n";   
    body += $.base64Encode(file.getAsBinary()) + "\r\n";  
    body += "--" + boundary + "--";
    xhr.sendAsBinary(body);

  }

1 个答案:

答案 0 :(得分:2)

IS 会花费大量的时间来填充文件的内容,base64对其进行编码,然后执行字符串连接。换句话说:按预期行事。