Как поместить файл изображения в объект json?
Я создаю базу данных для видеоигр, каждая из которых содержит такие элементы, как имя, жанр и образ игры. Можно ли поместить изображения в объект json для db? Если это не так?
6 ответов
Я могу думать о том, чтобы сделать это двумя способами:
Сохранение файла в файловой системе в любом каталоге (например, dir1 ) и переименование его, что гарантирует уникальность имени для каждого файла (может быть временной отметкой) (например, xyz123.jpg ), а затем сохранение этого имени в некоторые базы данных. Затем при создании JSON вы вытаскиваете это имя файла и генерируете полный URL (который будет http://example.com/dir1/xyz123.png ) и вставляете его в JSON.
Base 64 Encoding, Это в основном способ кодирования произвольных двоичных данных в тексте ASCII. Он занимает 4 символа на 3 байта данных, плюс, возможно, немного отступов в конце. По сути, каждый 6 бит ввода кодируется в 64-символьном алфавите. «Стандартный» алфавит использует A-Z, a-z, 0-9 и + и /, с = в качестве символа заполнения. Существуют варианты, защищенные URL-адресами. Таким образом, этот подход позволит вам разместить свое изображение непосредственно в MongoDB, сохраняя его. Кодируйте изображение и декодируйте его, извлекая его, у него есть свои недостатки:
- кодировка base64 делает размеры файлов примерно на 33% больше, чем их исходные двоичные представления, что означает больше данных по проводу (это может быть исключительно болезненно в мобильных сетях).
- данные URI поддерживаются в IE6 или IE7.
- Закодированные данные base64 могут потребовать больше времени, чем двоичные данные.
Преобразование изображения в URI UATA
A.) Холст
Загрузите изображение в Image-Object, нарисуйте его на холсте и преобразуйте холст обратно в dataURL.
Использование
Поддерживаемые форматы ввода image/png , image/jpeg , image/jpg , image/gif , image/bmp , image/tiff , image/x-icon , image/svg+xml , image/webp , image/xxx
B.) FileReader
Загрузите изображение как blob через XMLHttpRequest и используйте API FileReader для преобразования его в URL-адрес данных.
How do you put an image file in a json object?
I am making a database for video games, each containing elements like name, genre, and and image of the game. Is it possible to put images into a json object for the db? If not is there a way around this?
5 Answers 5
I can think of doing it in two ways:
Storing the file in file system in any directory (say dir1 ) and renaming it which ensures that the name is unique for every file (may be a timestamp) (say xyz123.jpg ), and then storing this name in some DataBase. Then while generating the JSON you pull this filename and generate a complete URL (which will be http://example.com/dir1/xyz123.png )and insert it in the JSON.
Base 64 Encoding, It’s basically a way of encoding arbitrary binary data in ASCII text. It takes 4 characters per 3 bytes of data, plus potentially a bit of padding at the end. Essentially each 6 bits of the input is encoded in a 64-character alphabet. The "standard" alphabet uses A-Z, a-z, 0-9 and + and /, with = as a padding character. There are URL-safe variants. So this approach will allow you to put your image directly in the MongoDB, while storing it Encode the image and decode while fetching it, it has some of its own drawbacks:
- base64 encoding makes file sizes roughly 33% larger than their original binary representations, which means more data down the wire (this might be exceptionally painful on mobile networks)
- data URIs aren’t supported on IE6 or IE7.
- base64 encoded data may possibly take longer to process than binary data.
Converting Image to DATA URI
A.) Canvas
Load the image into an Image-Object, paint it to a canvas and convert the canvas back to a dataURL.
Usage
Supported input formats image/png , image/jpeg , image/jpg , image/gif , image/bmp , image/tiff , image/x-icon , image/svg+xml , image/webp , image/xxx
B.) FileReader
Load the image as blob via XMLHttpRequest and use the FileReader API to convert it to a data URL.
Как загрузить локальные картинки в json?
У меня есть много картинок, и было бы классно иметь просто json file, откуда через итерацию можно был бы загружать в dom, но я не знаю как локальные картинки в json вставить или загрузить.

- Вопрос задан более года назад
- 2924 просмотра
Простой 1 комментарий
- Вконтакте

Можно ваши картинки собрать в один json файл. Все картинки желательно оптимизировать под размер и качество)
Дальше их можно сложить в base64 и запаковать в json.
Дальше итерироваться по json и создавать объект дома. Например тег img и указывать src подобным образом.
AJAX: Post JSON and Images
![]()
There is always a need for image transferring together with JSON files. I remember the time when I was still a front-end developer intern, as a rookie I really did not understand how to send images and JSON data to the backend. This was quite struggling as I tried my very best but not coming up with any solutions. I even once thought it was the back-end’s fault.
With the help from my colleagues, the issue was resolved eventually. The idea is to first create a FormData() constructor, append the image to formData, and finally fire an AJAX event with all the information needed. An example looks like this:
All information that is supposed to be wrapped in JSON is now appended as parameters. This could become quite messy when a larger bunch of information needs to be sent.
A better solution is to wrap the information into JSON and append it to formData. The following is written in Vue. Amend where needed.
And you might need to adjust your backend (with Spring MVC):
In the above Spring MVC example, apart from a file (the image), a JSON string is also required. Then the Jackson library is used to parse the JSON string.