Меню

Invalid stored block lengths ошибка как исправить

Я пытаюсь отправить некоторые сжатые данные по сети, я думаю, что данные успешно сжаты, так как я могу повторно раздуть их из кода, который выкачивает данные (написан на C), однако, когда данные поступают на мой сервер (nodejs используя экспресс) и пытается раздуть данные, которые я получаю:

{ Error: invalid stored block lengths
    at InflateRaw.zlibOnError (zlib.js:153:15) errno: -3, code: 'Z_DATA_ERROR' }

Любая помощь будет очень признательна, спасибо заранее.

Сзз.

П.Д.: Я могу предоставить вырезанный код, если он кому-нибудь пригодится.

Обновлено:

Спасибо за быстрый ответ и извините за задержку, я работал над своим кодом, теперь я отправляю исходные данные на сервер вместе со сжатыми данными. Когда исходные данные поступают на сервер, я сдуваю их, чтобы увидеть сгенерированные буферы, удивительно, что буферы сжатых данных, отправляемых по сети, и буфер, сжатый на сервере, в частности, являются одними и теми же кроме двух первых байтов:

<Buffer 78 da 15 8c c9 11 00 41 08 02 ff c6 82 55 83 b7 f9 27 b6 ee 13 68 7a a6 b0 4c b8 a7 68 ac 81 61 84 5a 8b e6 82 6b 05 bd aa 44 d9 5e a0 d7 20 6c 2f a6 ... >

<Buffer 15 8c c9 11 00 41 08 02 ff c6 82 55 83 b7 f9 27 b6 ee 13 68 7a a6 b0 4c b8 a7 68 ac 81 61 84 5a 8b e6 82 6b 05 bd aa 44 d9 5e a0 d7 20 6c 2f a6 bf 9b ... >

Итак, я думаю, что теперь мой вопрос заключается в том, могу ли я предположить, что эти первые два байта всегда будут появляться в сжатых данных из программы C? Есть ли возможность избежать этих первых двух байтов? Я делаю хорошо?

Здесь я оставляю вам функцию, которая сжимает данные в части C, нодовая часть — это просто огромный анализ пост-ввода и небольшая работа с буферами.

int compress_image (compressed_image raw, size_t size, compressed_image * out) {

    z_stream strm;
    int out_size = 0;

    *out = (compressed_image) malloc(size);

    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;

    int ret = deflateInit(&strm, Z_BEST_COMPRESSION); /* Max compression level, but bad speed performace */

    if (ret != Z_OK)
        return ret;

    strm.avail_in = size;
    strm.next_in = (unsigned char *)raw;

    do {

        strm.avail_out = size;
        strm.next_out = *out;
        ret = deflate(&strm, Z_FINISH);    /* no bad return value */
        assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
        out_size += (size - strm.avail_out);

    } while (strm.avail_out == 0);

    (void)deflateEnd(&strm);

    return out_size;
}

Еще раз спасибо!

Обновлено еще раз:
Сейчас я сбрасываю свои буферы и вижу, что некоторые конечные байты тоже отличаются,
здесь у вас есть буфер, поступающий из программы C:

00000000: 78da 158c c911 0041 0802 ffc6 8255 83b7  xÚ..É..A..ÿÆ.U.·
00000010: f927 b6ee 1368 7aa6 b04c b8a7 68ac 8161  ù'¶î.hz¦°L¸§h¬.a
00000020: 845a 8be6 826b 05bd aa44 d95e a0d7 206c  .Z.æ.k.½ªDÙ^.× l
00000030: 2fa6 bf9b 680e f2ce 9c67 975f 0e58 2d91  /¦¿.h.òÎ.g._.X-.
00000040: 75dc f1ed b25c 687a 43dd 42bc 1f98 e7dd  uÜñí²hzCÝB¼..çÝ
00000050: 79a7 99f6 5fd3 bfcc 86f2 01b0 f51a cd    y§.ö_Ó¿Ì.ò.°õ.Í

И буфер сдулся на сервере:

00000000: 158c c911 0041 0802 ffc6 8255 83b7 f927  ..É..A..ÿÆ.U.·ù'
00000010: b6ee 1368 7aa6 b04c b8a7 68ac 8161 845a  ¶î.hz¦°L¸§h¬.a.Z
00000020: 8be6 826b 05bd aa44 d95e a0d7 206c 2fa6  .æ.k.½ªDÙ^.× l/¦
00000030: bf9b 680e f2ce 9c67 975f 0e58 2d91 75dc  ¿.h.òÎ.g._.X-.uÜ
00000040: f1ed b25c 687a 43dd 42bc 1f98 e7dd 79a7  ñí²hzCÝB¼..çÝy§
00000050: 99f6 5fd3 bfcc 86f2 01   

Однако, создав новый буфер без первых двух байтов, я могу правильно раздуть свои данные на сервере:

Моя часть node.js:

const dump = require('buffer-hexdump');

router.post('/test', function(req, res, next) {

    let form = new formidable.IncomingForm();
    form.uploadDir = "./uploads"

    form.parse(req, function(err, fields, files) {

        let deflated = zlib.deflateRawSync(fs.readFileSync(files.image_raw.path));

        let image_buff = fs.readFileSync(files.image.path);
        let buff = Buffer.alloc(image_buff.length - 2);

        image_buff.copy(buff, 0, 2);

        console.info(buff.equals(deflated)); //false
        console.info(dump(deflated));
        console.info(dump(image_buff));

        zlib.inflateRaw(buff, (err, buffer) => {

            if (err)
                console.error(err);
            else
                console.info(buffer.toString()); //here I can see my data!!

        });

        res.status(200).send("POST received!");

    });
});

Однако я не думаю, что это решено…

Еще раз спасибо!

Сзз.

I am trying to extract a ZIP file from my current JAR using:

InputStream resource = getClass().getClassLoader().getResourceAsStream(name);

This get the correct InputStream, but it gives an error when I try to unzip it using the following code (I’m storing each file into a Hashmap<file, filename>):

public static HashMap<String, String> readZip(InputStream inputStream) throws IOException {
    byte[] buffer = new byte[1024];
    HashMap<String, String> list = new HashMap<>();
    ZipInputStream zipInputStream = new ZipInputStream(inputStream);
    ZipEntry entry = zipInputStream.getNextEntry();
    while (entry != null) {
        if (!entry.isDirectory()) {
            StringBuilder stringBuilder = new StringBuilder();
            while (IOUtils.read(zipInputStream, buffer) > 0) {
                stringBuilder.append(new String(buffer, "UTF-8"));
            }
            list.put(stringBuilder.toString(), entry.getName());
        }
        zipInputStream.closeEntry();
        entry = zipInputStream.getNextEntry();
    }
    zipInputStream.closeEntry();
    zipInputStream.close();
    return list;
}

However when I try to do this, I get this exception (on IOUtils.read)

java.util.zip.ZipException: invalid stored block lengths
   at java.util.zip.InflaterInputStream.read(Unknown Source)
   at java.util.zip.ZipInputStream.read(Unknown Source)

Am I doing this wrong? I’ve done plenty of googling of the error, and I didn’t see anything related to my issue.

I am running a Rails (3.2.3) application with Ruby 1.9.3p194 on the basic Ubuntu lucid32 image in a Vagrant virtual box. The virtual box is running on Leopard, for what it’s worth. I’m trying to use rubyzip in the application to decompress a zip archive — 2009_da_lmp.zip. Using code directly from examples in the rubyzip repository, I can confirm that I can list the archive file contents:

#f is the absolute path to 2009_da_lmp.zip (string)
Zip::ZipFile.open(f) { |zf| zf.entries[0] }  
 => 20090101_da_lmp.csv #that is indeed a file in the archive.

Using some more code from the examples in the repository, I try to get at an actual file in the archive:

Zip::ZipInputStream.open(f) { |zis|
  entry = zis.get_next_entry
  print "first line of '#{entry.name}' (#{entry.size} bytes: ) "
  puts "'#{zis.gets.chomp}'" }

=> first line of '20090101_da_lmp.csv' (826610 bytes: ) Zlib::DataError: 
   invalid stored block lengths #and a long stack trace I can provide 
                                #if that might help

The Mac OS decompression utility unzips the archive fine. I was wondering if it was some kind of encoding-related thing (my locale is set to en_US.UTF-8 because to make using PostgreSQL in dev less painful), but I don’t know how to tell if that’s the case. I can’t find any information on what might cause this error.

I am running a Rails (3.2.3) application with Ruby 1.9.3p194 on the basic Ubuntu lucid32 image in a Vagrant virtual box. The virtual box is running on Leopard, for what it’s worth. I’m trying to use rubyzip in the application to decompress a zip archive — 2009_da_lmp.zip. Using code directly from examples in the rubyzip repository, I can confirm that I can list the archive file contents:

#f is the absolute path to 2009_da_lmp.zip (string)
Zip::ZipFile.open(f) { |zf| zf.entries[0] }  
 => 20090101_da_lmp.csv #that is indeed a file in the archive.

Using some more code from the examples in the repository, I try to get at an actual file in the archive:

Zip::ZipInputStream.open(f) { |zis|
  entry = zis.get_next_entry
  print "first line of '#{entry.name}' (#{entry.size} bytes: ) "
  puts "'#{zis.gets.chomp}'" }

=> first line of '20090101_da_lmp.csv' (826610 bytes: ) Zlib::DataError: 
   invalid stored block lengths #and a long stack trace I can provide 
                                #if that might help

The Mac OS decompression utility unzips the archive fine. I was wondering if it was some kind of encoding-related thing (my locale is set to en_US.UTF-8 because to make using PostgreSQL in dev less painful), but I don’t know how to tell if that’s the case. I can’t find any information on what might cause this error.

У меня был похожий случай с действительно действительным ZIP-файлом, но мне было трудно прочитать его с помощью Java. Исключение было похоже на ваше, но с другой трассировкой стека:

Caused by: java.util.zip.ZipException: invalid stored block lengths
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:164)
at java.util.zip.ZipInputStream.read(ZipInputStream.java:194)
at java.util.zip.ZipInputStream.closeEntry(ZipInputStream.java:140)
at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:118)
...

В моем случае «неисправный» ZIP-файл был создан с помощью «архивного» модуля Ansible на компьютере с CentOS:

- name: Create a zip archive
  archive:
    path: /tmp/mydir/
    dest: /tmp/mydir.zip
    format: zip

Исправление заключалось в добавлении звездочки в конце «пути» при создании ZIP:

- name: Create a zip archive
  archive:
    path: /tmp/mydir/*
    dest: /tmp/mydir.zip
    format: zip

Содержимое двух ZIP-файлов одинаково, но есть некоторые различия в атрибутах файла/каталога в ZIP-файле, которые, по-видимому, вызывают проблему в Java.

Problem

Over the top Cognos installation fails with «invalid stored block lengths» exception message

Symptom

Following error occurs when an over-the-top Cognos installation is performed.

Error installing file: file_location_install_file.zip Exception Message: invalid stored block lengths Call Stack: java.util.zip.ZipException: invalid stored block lengths at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:175) at java.util.zip.ZipInputStream.read(ZipInputStream.java:205) at java.io.FilterInputStream.read(FilterInputStream.java:118) at java.nio.file.Files.copy(Files.java:2919) at java.nio.file.Files.copy(Files.java:3038) at manifest.Part.extractFile(Part.java:307) at manifest.Part.unpackZIP(Part.java:276) at manifest.Part.install(Part.java:213) at manifest.Part.install(Part.java:167) at InstallFromRepo.InstallParts(InstallFromRepo.java:384) at InstallFromRepo.install(InstallFromRepo.java:139) at com.zerog.ia.installer.actions.CustomAction.installSelf(Unknown Source) at com.zerog.ia.installer.InstallablePiece.install(Unknown Source) at com.zerog.ia.installer.InstallablePiece.install(Unknown Source) at com.zerog.ia.installer.InstallablePiece.install(Unknown Source) at com.zerog.ia.installer.InstallablePiece.install(Unknown Source) at com.zerog.ia.installer.GhostDirectory.install(Unknown Source) at com.zerog.ia.installer.InstallablePiece.install(Unknown Source) at com.zerog.ia.installer.Installer.install(Unknown Source) at com.zerog.ia.installer.actions.InstallProgressAction.ae(Unknown Source) at com.zerog.ia.installer.actions.ProgressPanelAction$1.run(Unknown Source)

Cause

Invalid write permission to the installation directory caused the issue.

Diagnosing The Problem

Everyone group did not have write permissions to the installation directory (755). Changing the permissions for everyone group to include write (777) resolved the issue.

Resolving The Problem

Giving write permission to everyone group (777) resolved the issue.

Document Location

Worldwide

[{«Type»:»MASTER»,»Line of Business»:{«code»:»LOB10″,»label»:»Data and AI»},»Business Unit»:{«code»:»BU059″,»label»:»IBM Software w/o TPS»},»Product»:{«code»:»SSTSF6″,»label»:»IBM Cognos Analytics»},»ARM Category»:[{«code»:»a8m50000000Cl3yAAC»,»label»:»Installation and Configuration»}],»ARM Case Number»:»TS007075607″,»Platform»:[{«code»:»PF016″,»label»:»Linux»}],»Version»:»All Versions»}]

Я пытаюсь извлечь ZIP-файл из моего текущего JAR, используя:

InputStream resource = getClass().getClassLoader().getResourceAsStream(name);

Это дает правильный InputStream, но выдает ошибку, когда я пытаюсь разархивировать его, используя следующий код (я сохраняю каждый файл в Hashmap<file, filename>):

public static HashMap<String, String> readZip(InputStream inputStream) throws IOException {
    byte[] buffer = new byte[1024];
    HashMap<String, String> list = new HashMap<>();
    ZipInputStream zipInputStream = new ZipInputStream(inputStream);
    ZipEntry entry = zipInputStream.getNextEntry();
    while (entry != null) {
        if (!entry.isDirectory()) {
            StringBuilder stringBuilder = new StringBuilder();
            while (IOUtils.read(zipInputStream, buffer) > 0) {
                stringBuilder.append(new String(buffer, "UTF-8"));
            }
            list.put(stringBuilder.toString(), entry.getName());
        }
        zipInputStream.closeEntry();
        entry = zipInputStream.getNextEntry();
    }
    zipInputStream.closeEntry();
    zipInputStream.close();
    return list;
}

Однако, когда я пытаюсь это сделать, я получаю исключение (IOUtils.read)

java.util.zip.ZipException: invalid stored block lengths
   at java.util.zip.InflaterInputStream.read(Unknown Source)
   at java.util.zip.ZipInputStream.read(Unknown Source)

Я делаю это неправильно? Я много раз искал ошибку в Google и не нашел ничего, связанного с моей проблемой.

3 ответа

Лучший ответ

Благодаря ответу @ PaulBGD выше. Это сэкономило мне часы, чтобы выяснить, что случилось с моей системой. Я добавляю следующие новые фрагменты в свой файл pom.xml (я не понимал, что это основная причина, прежде чем читать ответ Пола):

<resources>
  <resource>
    <directory>src/main/resources</directory>
    <filtering>true</filtering>
    <includes>
      <include>**/*.version</include>
      <include>**/*.properties</include>
      <include>**/*.xml</include>
      <include>**/*.csv</include>
      <include>**/*.txt</include>
      <include>**/*.gif</include>
      <include>**/*.json</include>
      <include>**/*.xlsx</include>
      <include>rythm/**</include>
    </includes>
  </resource>
</resources>

Однако я не принял ответ Пола напрямую, вместо этого я не думаю, что эти файлы xlsx должны проходить через конвейер фильтрации плагина ресурсов, поэтому я добавил еще один resource в pom:

  <resource>
    <directory>src/main/resources</directory>
    <filtering>false</filtering>
    <includes>
      <include>**/*.xlsx</include>
    </includes>
  </resource>

И это устранило мою проблему, не изменив настройку исходной кодировки с UTF-8 на ISO-8859-1


10

Gelin Luo
3 Май 2016 в 22:19

После еще нескольких часов поиска я декомпилировал maven-resources-plugin и заметил, что по умолчанию он использует кодировку UTF-8. Я быстро нашел нужную мне кодировку (ISO-8859-1) и вставил ее в свой файл pom.

<properties>
    <project.build.sourceEncoding>ISO-8859-1</project.build.sourceEncoding>
</properties>

Теперь zip-файл отлично копируется в банку, никаких повреждений.


7

PaulBGD
11 Авг 2014 в 16:37

Измените spring-boot-starter-parent на 2.0.4.RELEASE. У меня это сработало.

  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath />
    </parent>


0

Narendra Kekane
5 Окт 2018 в 14:57

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Invalid signature standoff 2 ошибка
  • Invalid shorthand property initializer ошибка js