PDA

View Full Version : add file in json structure



ms2222
23rd November 2014, 09:59
i want to add a file to json structure and send it,i want to add that file to json using json array for example i reading file as binary an append to json array(use this code) :

void send_file(QString file_path)
{
cout<<"SEND FILE: "<<file_path.toStdString()<<"\n";

QFile i_file(file_path.remove(file_path.count()-1,1));
i_file.open(QIODevice::ReadOnly);
if (i_file.isOpen())
{
QJsonObject packet;
packet["message_type"]="ANSWER_PACKET";
packet["sender"]=mac_address;
packet["reciver"]="control_panel";
packet["answer_type"]="PRIVATE";
packet["what"]="send_file";
packet["file_type"]="GENERAL";
packet["file_path"]=file_path;
QDataStream i_file_stream(&i_file);
QJsonArray i_array;
while (!i_file.atEnd())
{
int len=1048576;
char char_buffer[len];
int size_read=i_file_stream.readRawData(char_buffer,le n);
if (size_read>0)
{
QByteArray temp(char_buffer,size_read);
i_array.append(temp.constData());
}
}

packet["file_content"]=i_array;
QJsonDocument json_doc(packet);
QByteArray buffer=json_doc.toJson();

cout<<QString(buffer).toStdString()<<"\n";
i_file.close();
send_packet(buffer);

}
}

now,in another hand i using this code for deserializing and writing file:

void settings_frame_widget::save_file(QJsonObject packet)
{
QJsonArray i_array =packet["file_content"].toArray();
QByteArray file_buffer;

foreach (QJsonValue item, i_array)
{
QByteArray temp=item.toVariant().toByteArray();
file_buffer.append(temp);
}
//Write File:
if (download_address!=QString())
{
QFile i_file(download_address);
i_file.open(QIODevice::WriteOnly);
if (i_file.isOpen())
{
QDataStream file_stream(&i_file);
file_stream<<file_buffer;
}
QMessageBox msgbox;
msgbox.setText("Download Finish!");
msgbox.exec();
i_file.close();
download_address=QString();
}
}


for example when i send sequential file like this:

{
"res1":{
"isError":false,
"key":"1234566",
"data":{
"messages":"O.K!"
}
}
}
when recive it and write to file , see a slacks byte in first of file,like this:
10759
this sudden cause of random access file is damaged...
what's the problem!?

anda_skoa
23rd November 2014, 14:00
Not saying that this is the cause for your proble, but you are using asymmetric operations for reading and writing the file.

When reading you are getting raw bytes from the file, when writing you are writing QByteArray objects into a QDataStream.

If the file content is not data encoded by QDataStream but arbitrary binary content, then I would suggest to just read/write using the methods in QFile.

Cheers,
_

ChrisW67
25th November 2014, 20:33
You will probably have issues if you embed unencoded arbitrary binary data into a JSON structure which must remain compilable Javascript/parsable text.