Fileheader.readasbinareString для загрузки файлов

пытается использовать FialeReader.readasbinaryString, чтобы загрузить файл PNG на сервер через ajax, убранный код вниз (fileobject - это объект, содержащий информацию в моем файле);

var fileReader = new FileReader();

fileReader.onload = function(e) {
    var xmlHttpRequest = new XMLHttpRequest();
    //Some AJAX-y stuff - callbacks, handlers etc.
    xmlHttpRequest.open("POST", '/pushfile', true);
    var dashes = '--';
    var boundary = 'aperturephotoupload';
    var crlf = "\r\n";

    //Post with the correct MIME type (If the OS can identify one)
    if ( fileObject.type == '' ){
        filetype = 'application/octet-stream';
    } else {
        filetype = fileObject.type;
    }

    //Build a HTTP request to post the file
    var data = dashes + boundary + crlf + "Content-Disposition: form-data;" + "name=\"file\";" + "filename=\"" + unescape(encodeURIComponent(fileObject.name)) + "\"" + crlf + "Content-Type: " + filetype + crlf + crlf + e.target.result + crlf + dashes + boundary + dashes;

    xmlHttpRequest.setRequestHeader("Content-Type", "multipart/form-data;boundary=" + boundary);

    //Send the binary data
    xmlHttpRequest.send(data);
}

fileReader.readAsBinaryString(fileObject);

изучить первые несколько строк файла до Загрузка (с использованием VI) дает мне

enter image description here

один и тот же файл после загрузки показывает

enter image description here

, поэтому он выглядит как проблема форматирования / кодирования где-то, я пытался использовать простое функцию кодирования UTF8 в необработанных двоичных данных

    function utf8encode(string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    )

, затем в оригинале

    function utf8encode(string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    )

код

//Build a HTTP request to post the file
var data = dashes + boundary + crlf + "Content-Disposition: form-data;" + "name=\"file\";" + "filename=\"" + unescape(encodeURIComponent(file.file.name)) + "\"" + crlf + "Content-Type: " + filetype + crlf + crlf + utf8encode(e.target.result) + crlf + dashes + boundary + dashes;

, который дает мне вывод

enter image description here

еще не то, что был необработанным файлом = (

Как я могу кодировать / загрузить / обрабатывать файл, чтобы избежать проблем кодирования, поэтому файл, полученный в HTTP-запросе. Это так же, как файл, прежде чем он был загружен.

Некоторые другие возможно полезны, если вместо использования fileheader.readasbinareString () я использую fileobject.getAsbinary (), чтобы получить двоичные данные, это работает нормально. Но работает только в Getasbinary в Firefox. Я проверял это в Firefox и Chrome, как на Mac, получая тот же результат в обоих. Бенден D Загрузки обрабатываются модулем загрузки Nginx , снова работает на Mac. Сервер и клиент находятся на одной машине. То же самое происходит с любым файлом, который я пытаюсь загрузить, я просто выбрал PNG, потому что это был самый очевидный пример.

78
задан Smudge 15 September 2011 в 13:07
поделиться