QT-应用(5)-TCPClient-传送文件(文本-视频)

ubuntu 和windows下都可以运行的 demo
功能:1.连接服务器端
2.传送文件:文本或者视频
关键代码如下:
//QFile 小文件,一次性操作
void mytcpclientfile::on_uploadfile_btn_clicked()
{
QString msg;
QFile *pf;
pf=new QFile();
//1.选取上传文件 全路径:filename QFileDialog
QString filename=QFileDialog::getOpenFileName(this,"uploadfiles",
"D:\\QTPrj\\mytcpclientfile\\upfiles\\","(*.*)");
if(filename.isEmpty())
{
return;
}
msg=QString("1.选取上传文件 全路径:filename:%1").arg(filename);
ui->msg_textedit->append(msg);
pf->setFileName(filename);
bool ret=pf->open(QIODevice::ReadOnly|QIODevice::Unbuffered);
if(!ret)
{
return;
}
ui->uploadfiles_progressBar->setValue(0);
this->totalsize_=0;
this->sendsize_=0;
this->totalsize_=pf->size();
ui->uploadfiles_progressBar->setRange(0,this->totalsize_);
msg=QString("2.:发送的文件 filename:%1 ok 文件大小为:%2").arg(filename).arg(totalsize_);
ui->msg_textedit->append(msg);
//3.发送头给服务器 eg:filename#totalsize#
QFileInfo info(filename);
QString sendcontent=QString("%1#%2#")
.arg(info.fileName())
.arg(this->totalsize_);
ptcpsocket_->write(sendcontent.toUtf8());
ptcpsocket_->waitForBytesWritten();
msg=QString("3.socket发送给服务器 eg:filename#totalsize# :%1").arg(sendcontent);
ui->msg_textedit->append(msg);
qint64 len;
while(!pf->atEnd())
{
QByteArray ba=pf->read(MSG_LEN);
len=ptcpsocket_->write(ba);
this->sendsize_+=len;
ui->uploadfiles_progressBar->setValue(this->sendsize_);
ptcpsocket_->waitForBytesWritten();
}
pf->close();
//5.返回信息
if(this->totalsize_==this->sendsize_)
{
msg=QString("上传文件成功!");
}
else
{
msg=QString("上传文件失败! totalsize:%1 sendsize:%2")
.arg(this->totalsize_).arg(this->sendsize_);
}
ui->msg_textedit->append(msg);
}

浙公网安备 33010602011771号