We added a line edit to save path of file to be uploaded,First user clicks on Browse button then FileOpenDialogBox is shown from which selected file path comes in LineEdit.After that he clicks on upload button the file get copied to uploads folder beside executable.
On Browse button click we have following code
QString fileName = QFileDialog::getOpenFileName(this,tr("Libre Office File"),
"",tr("Libre Office File (*.odt);;All Files (*)")); ui->lineEdit->setText(fileName); which basically select file and save path to LineEdit. On click of upload button we have following code //current working directory QString location = QDir::currentPath() + "/uploads"; qDebug() << "Current working Dir:" +location ; //create directory if not exist if (! QDir(location).exists()) { QDir().mkdir(location); qDebug() << "Creating Path:" +location ; } //source path QString source = ui->lineEdit->text(); //get file name to append to destination path QFileInfo fi(source); QString name = fi.fileName(); //to make filename unique appending timestamp QString time = QString::number(QDateTime::currentMSecsSinceEpoch()); //make to be full destination file path QString destination = QDir(location).filePath(time + "_" + name); qDebug() << "Destination:" +destination; bool status = QFile::copy(ui->lineEdit->text(),destination); if(status) { QMessageBox::information(this,"Upload Status","File Uploaded Successfully at " + location); ui->lineEdit->setText(""); }else{ QMessageBox::warning(this,"Upload Status","File Upload at " + location + " Failed"); }
It first takes current working Directory appends uploads to end in path,then create directory if not exist. Now to avoid same file name upload overwrite file we are appending timestamp to destination filename.Latter on status of copy we are showing corresponding Message.
Point to note that destination path is not project folder but path where executable is generated for debug.
Code for project is avilable at https://github.com/gitsangramdesai/Qt-CPP-FileUploads.
No comments:
Post a Comment