Javascript не загружает двоичные данные - PullRequest
5 голосов
/ 23 сентября 2011

Моя функция JavaScript корректно загружает только текстовые файлы. Кто-нибудь может помочь мне понять, как заставить его также принимать изображения и т. Д.?

function fileUpload(files) {
  if (!files.length) {  
   fileList.innerHTML = "<p>No files selected!</p>";  
  } else {    
var list = document.createElement("ul");

for (var i = 0; i < files.length; i++) {

  //Set vars
  var file = files[i],
  fileName = file.name,
  fileSize = file.size,  
  fileData = file.getAsBinary(),  
  boundary = "xxxxxxxxx",  
  uri = "receive.php",

  //Create file info HTML output
  li = document.createElement("li");  
  list.appendChild(li);
  var info = document.createElement("span");  
  info.innerHTML = file.name + ": " + file.size + " bytes";  
  li.appendChild(info);

  //Start sending file
  var xhr = new XMLHttpRequest();
  xhr.open("POST", uri, true);  
  xhr.setRequestHeader("Content-Type", "multipart/form-data, boundary="+boundary); // simulate a file MIME POST request.

  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='" + fileName + "'\r\n";  
  body += "Content-Type: application/octet-stream\r\n\r\n";  
  body += fileData + "\r\n";  
  body += "--" + boundary + "--";  

  xhr.send(body);  

}  
fileList.appendChild(list);
return true;
  }
}

Обновление: я обнаружил следующую функцию онлайн на http://code.google.com/p/html5uploader/, но не могу понять, как применить ее к моей текущей функции. Xhr.sendAsBinary - единственное, что изменилось?

// Upload image files
upload = function(file) {

    // Firefox 3.6, Chrome 6, WebKit
    if(window.FileReader) { 

        // Once the process of reading file
        this.loadEnd = function() {
            bin = reader.result;                
            xhr = new XMLHttpRequest();
            xhr.open('POST', targetPHP+'?up=true', true);
            var boundary = 'xxxxxxxxx';
            var body = '--' + boundary + "\r\n";  
            body += "Content-Disposition: form-data; name='upload'; filename='" + file.name + "'\r\n";  
            body += "Content-Type: application/octet-stream\r\n\r\n";  
            body += bin + "\r\n";  
            body += '--' + boundary + '--';      
            xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
            // Firefox 3.6 provides a feature sendAsBinary ()
            if(xhr.sendAsBinary != null) {
                xhr.sendAsBinary(body); 
*snip*

1 Ответ

2 голосов
/ 23 сентября 2011

Существует пример W3C отправки изображения GIF с использованием multipart/form-data при http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2:

Content-Type: multipart/form-data; boundary=AaB03x

--AaB03x
Content-Disposition: form-data; name="submit-name"

Larry
--AaB03x
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=BbC04y

--BbC04y
Content-Disposition: file; filename="file1.txt"
Content-Type: text/plain

... contents of file1.txt ...
--BbC04y
Content-Disposition: file; filename="file2.gif"
Content-Type: image/gif
Content-Transfer-Encoding: binary

...contents of file2.gif...
--BbC04y--
--AaB03x--

Обратите внимание на дополнительную строку Content-Transfer-Encoding: binary. Попробуйте добавить это.

РЕДАКТИРОВАТЬ: Попробуйте Base64-кодирование данных файла, используя плагин Base64 jQuery :

  var body = "--" + boundary + "\r\n";
  body += "Content-Disposition: form-data; name='upload'; filename='" + fileName + "'\r\n";
  body += "Content-Type: application/octet-stream\r\n";
  body += "Content-Transfer-Encoding: base64\r\n\r\n";
  body += $.base64Encode(fileData) + "\r\n";
  body += "--" + boundary + "--";
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...