Narendra Acharya
Narendra Acharya

Reputation: 3

Reading binary data in elisp

I am trying to transport a blob of binary data from a file (PNG image) over XML-RPC in elisp. This is part of automatically uploading attachments to the Confluence wiki, specifically local images used in the current page. The code doing this is:

        ;; Open the file and get content
        (with-temp-buffer
          ;; file-name is the PNG file name, which is binary data
          (find-file (expand-file-name file-name current-dir))
          ;; Setup Confluence request alist
          (setq confl-req (list 
                           (cons "fileName" file-name)
                           (cons "contentType" mime-type)))
          ;; RPC call
          (setq confl-reply (cfln-rpc-execute 'confluence1.addAttachment
                                              page-id confl-req (buffer-substring-no-properties (point-min) (point-max))))

I am having a problem with the piece (buffer-substring-no-properties (point-min) (point-max)). The binary data uploaded to Confluence does not match the PNG file at couple of locations. I noticed that the bytes 0xe0 0x88 were replaced with 0xc8 in the attached file. Any idea how to get the exact binary data contained in a file?

Thanks, NMA

Upvotes: 0

Views: 1528

Answers (2)

Gizmomogwai
Gizmomogwai

Reputation: 2536

a one stop solution that goes in the line of @npostavs answer is provided by the f-library: https://github.com/rejeep/f.el

f-read-bytes

it uses

insert-file-contents-literally

together with

buffer-substring-no-properties

takes care of encoding and multibyte handling ....

Upvotes: 0

npostavs
npostavs

Reputation: 5027

You should use insert-file-contents-literally instead of find-file.

(insert-file-contents-literally FILENAME &optional VISIT BEG END
REPLACE)

Like `insert-file-contents', but only reads in the file literally.
A buffer may be modified in several ways after reading into the buffer,
to Emacs features such as format decoding, character code
conversion, `find-file-hook', automatic uncompression, etc.

This function ensures that none of these modifications will take place.

Upvotes: 3

Related Questions