void Shoter::onButtonSendClicked() { /*Create file */ QDate date = QDate::currentDate(); QString name_file = date.toString(); QString savedFile = name_file+".png"; QTemporaryFile file; file.setFileName(savedFile); if (!m_screenshot.save(&file)) { qDebug("file is not saved"); exit(1); } // qDebug()<<file.fileName(); QFile *openFile = new QFile(savedFile); openFile->open(QIODevice::ReadOnly); QHttpMultiPart *multi = new QHttpMultiPart(QHttpMultiPart::FormDataType); /* Upload to ipix.su */ if (ui->comboBox->currentIndex()== 0) { QHttpPart file; file.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("image/png")); file.setHeader(QNetworkRequest::ContentDispositionHeader,QVariant("form-data; name=\"file\"; filename=\""+savedFile+"\"")); file.setBodyDevice(openFile); openFile->setParent(multi); multi->append(file); this->upload("http://ipix.su/api/upload",multi); /* upload to pix.academ.org */ } else if (ui->comboBox->currentIndex() == 1) { QHttpPart action; action.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("name=\"action\"")); action.setBody("upload_image"); QHttpPart image; image.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/png")); image.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"image\"; filename=\""+savedFile+"\"")); image.setBodyDevice(openFile); openFile->setParent(multi); multi->append(action); multi->append(image); upload("http://pix.academ.org", multi); /* Upload to ompldr.org*/ } else if (ui->comboBox->currentIndex() == 2) { QHttpPart file1; file1.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/png")); file1.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file1\"; filename=\""+savedFile+"\"")); file1.setBodyDevice(openFile); openFile->setParent(multi); multi->append(file1); upload("http://ompldr.org/upload", multi); } }
void IVEFStreamHandler::connectToServer(QString host, int port, QString user, QString password, QString logFileName, bool slipstream, bool statistics) { QString portString; portString.setNum(port); std::cout << QString("iListen opening connection to %1:%2").arg(host, portString).toLatin1().data() << std::endl; // should we use keep track of line load m_statistics = statistics; // should we use compression m_slipstream = slipstream; // setup the socket m_tcpSocket->connectToHost(host, port); // store some info for the login m_user = user; m_password = password; #ifdef HAVE_ZLIB // setup decompression mechanism // we cannot use Qt for decompression since we do not know where the chunk starts or ends. if ( m_slipstream ) { m_strm.zalloc = Z_NULL; m_strm.zfree = Z_NULL; m_strm.opaque = Z_NULL; m_strm.avail_in = 0; m_strm.next_in = Z_NULL; if (inflateInit(&m_strm) != Z_OK) { std::cout << "iListen error initiating zlib stream" << std::endl; } } #endif // set a timer to check the bytes in/out every minte if ( m_statistics ) { QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(slotStatisticsTimerFired())); timer->start(TIMER_INTERVAL*1000); } // setup the logstream if needed if (logFileName != "") { QFile* file = new QFile(logFileName); file->setParent(this); // make sure it gets cleaned up if (!file->open(QIODevice::WriteOnly | QIODevice::Text)) { std::cerr << QString("iListen error opening file: %1 for writing").arg(logFileName).toLatin1().data() << std::endl; std::exit(1); } m_log = new QTextStream(file); m_log->setCodec("UTF-8"); *m_log << "<xml>\n"; // create a start tag m_log->flush(); } else { m_log = NULL; } }
void Syncer::send(QMap<QString, QString>& posts, QStringList& files) { QNetworkRequest request(QUrl(url + posts["command"])); QHttpMultiPart* parts = new QHttpMultiPart(QHttpMultiPart::FormDataType); QMapIterator<QString, QString> i(posts); while (i.hasNext()) { i.next(); QHttpPart* part = new QHttpPart(); part->setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\""+ i.key() +"\"")); part->setBody(i.value().toUtf8()); parts->append(*part); } foreach (QString filename, files) { QFileInfo finfo(filename); QFile* file = new QFile(finfo.absoluteFilePath()); if (file->open(QIODevice::ReadOnly)) { QHttpPart* part = new QHttpPart(); part->setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/"+ finfo.suffix().toLower() +"")); part->setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; filename=\""+ finfo.fileName() +"\"")); part->setBodyDevice(file); file->setParent(parts); // for delete time parts->append(*part); } }
void MockGeoNetworkReply::setFile(QFile* file) { delete m_file; m_file = file; if (m_file) m_file->setParent(this); }
bool ServerListener::postTaskResults(QString taskId, QString filepath) { QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart textPart; textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"task_assignment_id\"")); textPart.setBody(taskId.toUtf8()); QHttpPart filePart; filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain")); filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("attachment; name=\"result_file\"; filename=\"out.csv\"")); QFile *file = new QFile(filepath); file->open(QIODevice::ReadOnly); filePart.setBodyDevice(file); file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart multiPart->append(textPart); multiPart->append(filePart); QEventLoop loop; QNetworkAccessManager* manager = new QNetworkAccessManager(); QNetworkRequest request = QNetworkRequest(QUrl(ClientSettingsManager::getServerUrl() + "postTaskData")); connect(manager, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit())); manager->post(request, multiPart); loop.exec(); file->close(); delete multiPart; delete manager; return true; }
void imgUploader::uploadImage(QString FileName, QString PhpUploadURL, QString FieldName) { QUrl serviceUrl = QUrl(PhpUploadURL); QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QNetworkRequest request(serviceUrl); request.setRawHeader("User-Agent", UserAgent.toAscii()); QHttpPart imagePart; imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg")); imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"" + FieldName + "\"; filename=\"" + FileName + "\"")); QFile *file = new QFile(FileName); file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart file->open(QIODevice::ReadOnly); imagePart.setBodyDevice(file); multiPart->append(imagePart); // Call the webservice //QNetworkAccessManager *networkManager = new QNetworkAccessManager(this); currentUpload = manager.post(request, multiPart); connect(currentUpload,SIGNAL(uploadProgress(qint64,qint64)),this, SLOT(onUploadProgress(qint64,qint64))); connect(currentUpload, SIGNAL(finished()),this,SLOT(onUploadFinished())); Uploading = true; //reply->deleteLater(); }
QString ccloud::uploadHtmlSchedule(QString htmlpath) { qDebug() << "upload test"; QFile *file = new QFile( htmlpath ); QFileInfo info( htmlpath ); if (!file->exists()){ qDebug() << "file not exists"; return ""; } QSettings settings; QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart textPart; textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"upload\"")); textPart.setBody("upload"); QHttpPart userPart; userPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"user_id\"")); userPart.setBody( settings.value("cloud/id").toString().toLatin1() ); QHttpPart filePart; filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/html")); filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant( QString("form-data; name=\"userfile\"; filename=\"%1\"").arg( info.fileName() ))); file->open(QIODevice::ReadOnly); filePart.setBodyDevice(file); file->setParent(multiPart); multiPart->append(textPart); multiPart->append(userPart); multiPart->append(filePart); QUrl url("https://api.theocbase.net/theocbase_get.php"); QNetworkRequest request(url); QNetworkAccessManager *manager = new QNetworkAccessManager(this); QNetworkReply *reply = manager->post(request,multiPart); multiPart->setParent(reply); QEventLoop loop; connect(reply,SIGNAL(finished()),&loop,SLOT(quit())); loop.exec(); QString replystr = reply->readAll(); if (reply->error() == QNetworkReply::NoError) { if (replystr == "true"){ return "https://schedule.theocbase.net/" + info.fileName(); }else{ return ""; } } else { QMessageBox::information(0,"","Error when uploding html-schedule to cloud\n" + reply->errorString()); return ""; } }
void DriveManager::handleUploadRequestFinished () { QNetworkReply *reply = qobject_cast<QNetworkReply*> (sender ()); if (!reply) return; reply->deleteLater (); QString path = Reply2FilePath_.take (reply); const int code = reply-> attribute (QNetworkRequest::HttpStatusCodeAttribute).toInt (); if (code != 200) { qWarning () << Q_FUNC_INFO << "upload initiating failed with code:" << code; return; } emit uploadStatusChanged (tr ("Uploading..."), path); QFile *file = new QFile (path); if (!file->open (QIODevice::ReadOnly)) { qWarning () << Q_FUNC_INFO << "unable to open file: " << file->errorString (); return; } QUrl url (reply->rawHeader ("Location")); QNetworkRequest request (url); #ifdef HAVE_MAGIC request.setHeader (QNetworkRequest::ContentTypeHeader, magic_file (Magic_, path.toUtf8 ())); #endif request.setHeader (QNetworkRequest::ContentLengthHeader, QString::number (QFileInfo (path).size ()).toUtf8 ()); QNetworkReply *uploadReply = Core::Instance ().GetProxy ()-> GetNetworkAccessManager ()->put (request, file); file->setParent (uploadReply); Reply2FilePath_ [uploadReply] = path; connect (uploadReply, SIGNAL (finished ()), this, SLOT (handleUploadFinished ())); connect (uploadReply, SIGNAL (error (QNetworkReply::NetworkError)), this, SLOT (handleUploadError (QNetworkReply::NetworkError))); connect (uploadReply, SIGNAL (uploadProgress (qint64, qint64)), this, SLOT (handleUploadProgress (qint64, qint64))); }
void LoginManager::upload(const QString &path, int nid, const QString &title, const QString &description, const QString& priv, const QString& license, const QString& tags) { //qDebug() << "file upload"; KQOAuthRequest *oauthRequest = new KQOAuthRequest(this); QUrl url("https://api.musescore.com/services/rest/score.json"); if (nid > 0) url = QUrl(QString("https://api.musescore.com/services/rest/score/%1/update.json").arg(nid)); oauthRequest->initRequest(KQOAuthRequest::AuthorizedRequest, url); oauthRequest->setConsumerKey(_consumerKey); oauthRequest->setConsumerSecretKey(_consumerSecret); oauthRequest->setToken(_accessToken); oauthRequest->setTokenSecret(_accessTokenSecret); oauthRequest->setContentType("multipart/form-data"); QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart filePart; filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/octet-stream")); filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"score_data\"; filename=\"temp.mscz\"")); QFile *file = new QFile(path); file->open(QIODevice::ReadOnly); filePart.setBodyDevice(file); file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart multiPart->append(filePart); QHttpPart titlePart; titlePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"title\"")); titlePart.setBody(title.toUtf8()); multiPart->append(titlePart); QHttpPart descriptionPart; descriptionPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"description\"")); descriptionPart.setBody(description.toUtf8()); multiPart->append(descriptionPart); QHttpPart privatePart; privatePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"private\"")); privatePart.setBody(priv.toUtf8()); multiPart->append(privatePart); QHttpPart licensePart; licensePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"license\"")); licensePart.setBody(license.toUtf8()); multiPart->append(licensePart); QHttpPart tagsPart; tagsPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"tags\"")); tagsPart.setBody(tags.toUtf8()); multiPart->append(tagsPart); connect(_oauthManager, SIGNAL(requestReady(QByteArray)), this, SLOT(onUploadRequestReady(QByteArray))); oauthRequest->setHttpMultiPart(multiPart); _oauthManager->executeRequest(oauthRequest); }
void ImgurUploader::upload(const QString &fileName) { QFile *file = new QFile(fileName); if (!file->open(QIODevice::ReadOnly)) { emit error(ImageUploader::FileError, tr("Unable to read screenshot file"), fileName); file->deleteLater(); return; } QNetworkRequest request(QUrl("https://api.imgur.com/3/image")); request.setRawHeader("Authorization", QString("Client-ID %1").arg(clientId()).toLatin1()); QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); if (!mSettings.value("anonymous", true).toBool()) { request.setRawHeader("Authorization", QByteArray("Bearer ") + mSettings.value("access_token").toByteArray()); if (!mSettings.value("album").toString().isEmpty()) { QHttpPart albumPart; albumPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"album\"")); albumPart.setBody(mSettings.value("album").toByteArray()); multiPart->append(albumPart); } } QHttpPart imagePart; imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QMimeDatabase().mimeTypeForFile(fileName, QMimeDatabase::MatchExtension).name()); imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"image\"")); imagePart.setBodyDevice(file); file->setParent(multiPart); multiPart->append(imagePart); QNetworkReply *reply = Uploader::network()->post(request, multiPart); reply->setProperty("fileName", fileName); this->setProperty("fileName", fileName); multiPart->setParent(reply); #ifdef Q_OS_WIN connect(reply, &QNetworkReply::sslErrors, [reply](const QList<QSslError> &errors) { Q_UNUSED(errors); if (QSysInfo::WindowsVersion <= QSysInfo::WV_2003) { reply->ignoreSslErrors(); } }); #endif connect(reply, &QNetworkReply::uploadProgress, this, &ImgurUploader::uploadProgress); connect(this , &ImgurUploader::cancelRequest, reply, &QNetworkReply::abort); connect(this , &ImgurUploader::cancelRequest, reply, &QNetworkReply::deleteLater); connect(reply, &QNetworkReply::finished, this, &ImgurUploader::finished); }
void NetworkComm::addFile(QString key, const QByteArray value, const QByteArray file_extension, const QByteArray file_type){ QHttpPart* filePart; filePart = new QHttpPart(); filePart->setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\""+key+"\"; filename=\""+"myfile."+file_extension+"\"")); filePart->setHeader(QNetworkRequest::ContentTypeHeader, QVariant(file_type)); QFile *file = new QFile(value); file->open(QIODevice::ReadOnly); filePart->setBodyDevice(file); file->setParent(multiPart); multiPart->append(*filePart); }
void NetworkComm::addImage(QString key, const QByteArray value){ QHttpPart* imagePart; imagePart = new QHttpPart(); imagePart->setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\""+key+"\"; filename=\"myfile.jpg\"")); imagePart->setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg")); QFile *file = new QFile(value); file->open(QIODevice::ReadOnly); imagePart->setBodyDevice(file); file->setParent(multiPart); multiPart->append(*imagePart); //params.addQueryItem(key,value); }
void Toasty::slotNotify(Snore::Notification notification) { QString key = settingsValue(ToastyConstants::DeviceID).toString(); if (key.isEmpty()) { return; } QNetworkRequest request(QUrl::fromUserInput(QLatin1String("http://api.supertoasty.com/notify/") + key)); QHttpMultiPart *mp = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart title; title.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(QLatin1String("form-data; name=\"title\""))); title.setBody(notification.title().toUtf8().constData()); mp->append(title); QHttpPart text; text.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(QLatin1String("form-data; name=\"text\""))); text.setBody(notification.text().toUtf8().constData()); mp->append(text); QHttpPart app; app.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(QLatin1String("form-data; name=\"sender\""))); app.setBody(notification.application().name().toUtf8().constData()); mp->append(app); QHttpPart icon; icon.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(QLatin1String("form-data; name=\"image\"; filename=\"") + notification.icon().localUrl(QSize(128, 128)) + QLatin1Char('"'))); icon.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(QLatin1String("image/png"))); QFile *file = new QFile(notification.icon().localUrl(QSize(128, 128))); file->open(QIODevice::ReadOnly); icon.setBodyDevice(file); mp->append(icon); QNetworkReply *reply = m_manager.post(request, mp); mp->setParent(reply); file->setParent(reply); connect(reply, &QNetworkReply::finished, [reply]() { qCDebug(SNORE) << reply->error(); qCDebug(SNORE) << reply->readAll(); reply->close(); reply->deleteLater(); }); }
QNetworkReply* MNetworkManager::sendJWT(const QString url, QJsonObject ¶ms, QString method, const QString snapshotUrl, quint32 timestamp) { QJsonObject header; header["typ"] = "JWT"; header["alg"] = "sha256"; QByteArray encode; encode.append(QJsonDocument(header).toJson().toBase64(QByteArray::Base64Encoding)); encode.append("."); encode.append(QJsonDocument(params).toJson().toBase64(QByteArray::Base64Encoding)); QByteArray signature = QMessageAuthenticationCode::hash(encode, QByteArray(SECRET), QCryptographicHash::Sha256).toHex(); QByteArray jwt; jwt.append(encode); jwt.append("."); jwt.append(signature); QString apiUrl = APIHOST; apiUrl.append(url); QNetworkRequest request; request.setUrl(QUrl(apiUrl)); request.setRawHeader("JWT", jwt); QNetworkReply* reply; QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart imagePart; imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/png")); imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"screenshot_" + QString("%1").arg(timestamp) + "\"; filename=\"screenshot.jpg\"")); QFile *file = new QFile(snapshotUrl); file->open(QIODevice::ReadOnly); imagePart.setBodyDevice(file); file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart multiPart->append(imagePart); if (method == "post") { reply = this->post(request, multiPart); } else { reply = this->get(request); } multiPart->setParent(reply); reply->setProperty("imagePath", snapshotUrl); reply->setProperty("timestamp", timestamp); return reply; }
bool FstReader::addPart(const QString &path, const QString& name) { QFile* file = new QFile(path); if (!file->open(QIODevice::ReadOnly)) { qDebug() << "[ERROR] Couldn't open " << file->fileName(); return false; } QHttpPart part; part.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data;" " name=\"" + name.toUtf8() + "\";" " filename=\"" + QFileInfo(*file).fileName().toUtf8() + "\""); part.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-stream"); part.setBodyDevice(file); _dataMultiPart->append(part); file->setParent(_dataMultiPart); return true; }
void Snapshot::uploadSnapshot(const QString& filename, const QUrl& href) { const QString SNAPSHOT_UPLOAD_URL = "/api/v1/snapshots"; QUrl url = href; if (url.isEmpty()) { SnapshotMetaData* snapshotData = Snapshot::parseSnapshotData(filename); if (snapshotData) { url = snapshotData->getURL(); } delete snapshotData; } if (url.isEmpty()) { url = QUrl(DependencyManager::get<AddressManager>()->currentShareableAddress()); } SnapshotUploader* uploader = new SnapshotUploader(url, filename); QFile* file = new QFile(filename); Q_ASSERT(file->exists()); file->open(QIODevice::ReadOnly); QHttpPart imagePart; if (filename.right(3) == "gif") { imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/gif")); } else { imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg")); } imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"image\"; filename=\"" + file->fileName() + "\"")); imagePart.setBodyDevice(file); QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart multiPart->append(imagePart); auto accountManager = DependencyManager::get<AccountManager>(); JSONCallbackParameters callbackParams(uploader, "uploadSuccess", uploader, "uploadFailure"); accountManager->sendRequest(SNAPSHOT_UPLOAD_URL, AccountManagerAuth::Required, QNetworkAccessManager::PostOperation, callbackParams, nullptr, multiPart); }
void ChooseFileDlg::onFileSelect(bool) { QString path = QFileDialog::getOpenFileName(this, tr("Open File"), NULL, tr("All files *.*")); QFile *file = new QFile(path); if (!file->exists() || !file->open(QIODevice::ReadOnly)) return; QProgressDialog progress(tr("Uploading..."), tr("Abort"), 0, 100, this); progress.setMinimumDuration(0); QHttpPart httpFilePart; httpFilePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(QString("form-data; name=\"file\"; filename=\"%1\"").arg(QFileInfo(path).fileName()))); httpFilePart.setBodyDevice(file); QHttpMultiPart *httpMultiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); httpMultiPart->append(httpFilePart); QNetworkAccessManager manager; QNetworkReply *reply = manager.post(QNetworkRequest(QUrl("http://127.0.0.1:3000/media/upload")), httpMultiPart); connect(reply, &QNetworkReply::uploadProgress, [&](qint64 bytesSent, qint64 bytesTotal){ if (bytesSent && bytesTotal) progress.setValue((100 * bytesSent) / bytesTotal); }); file->setParent(httpMultiPart); httpMultiPart->setParent(reply); connect(&progress, &QProgressDialog::canceled, [&]() { reply->abort(); }); while (reply->isRunning()) { QCoreApplication::processEvents(); } if (reply->error() != QNetworkReply::NoError) { if (reply->error() != QNetworkReply::OperationCanceledError) QMessageBox::warning(this, tr("Failed to upload"), reply->errorString()); return; } QByteArray content = reply->readAll(); qDebug() << content; }
void SnapshotShareDialog::uploadSnapshot() { if (AccountManager::getInstance().getAccountInfo().getDiscourseApiKey().isEmpty()) { QMessageBox::warning(this, "", "Your Discourse API key is missing, you cannot share snapshots. Please try to relog."); return; } if (!_networkAccessManager) { _networkAccessManager = new QNetworkAccessManager(this); } QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart apiKeyPart; apiKeyPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"api_key\"")); apiKeyPart.setBody(AccountManager::getInstance().getAccountInfo().getDiscourseApiKey().toLatin1()); QFile* file = new QFile(_fileName); file->open(QIODevice::ReadOnly); QHttpPart imagePart; imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg")); imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\"; filename=\"" + file->fileName() +"\"")); imagePart.setBodyDevice(file); file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart multiPart->append(apiKeyPart); multiPart->append(imagePart); QUrl url(FORUM_UPLOADS_URL); QNetworkRequest request(url); QNetworkReply* reply = _networkAccessManager->post(request, multiPart); connect(reply, &QNetworkReply::finished, this, &SnapshotShareDialog::uploadRequestFinished); QEventLoop loop; connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit); loop.exec(); }
/** * @brief Function that sends the multipart message request to the API server. * Shows the image being OCR'd in the left-hand side of the interface */ void MainWindow::recognize(){ QHttpMultiPart* multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType); //set up http part message to send to api that contains image data QHttpPart imagePart; imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/gif")); imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\"; filename=\"./Polish_test2.gif\"")); QFile* file = new QFile(fileName); //debugging: make sure file was uploaded if(!file->open(QIODevice::ReadOnly)){ qDebug() << "# Could not upload/open file"; } QByteArray fileContent(file->readAll()); imagePart.setBody(fileContent); //append image data, api key, language, and overlay setting to multipart multipart->append(imagePart); multipart->append(part_parameter("apikey","3653fc62e388957")); multipart->append(part_parameter("language","pol")); multipart->append(part_parameter("isOverlayRequired","false")); //ocr api url QUrl api_url("https://apifree2.ocr.space/parse/image"); //create network request obj that contains the api url QNetworkRequest api_request(api_url); manager = new QNetworkAccessManager; //=(url, multipart encoded message) reply = manager->post(api_request, multipart); QObject::connect(reply, SIGNAL(finished()), this, SLOT(networkData())); //debugging: make sure file was opened; if 0 bytes, it wasn't! qDebug() << file->size() << "bytes"; imagePart.setBodyDevice(file); file->setParent(multipart); networkData(); }
fileUploader::fileUploader(QString filePath, QUrl url, QObject *parent) : QObject(parent) { QHttpMultiPart* multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart uploaderPart; uploaderPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"uploaderId\"")); //uploaderPart.setBody(UserObjectId); QFile* file = new QFile(filePath); file->open(QIODevice::ReadOnly); QHttpPart filePart; filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\"")); filePart.setBodyDevice(file); file->setParent(multipart); multipart->append(uploaderPart); multipart->append(filePart); QNetworkRequest request(QUrl(SERVER_FILE)); _networkManager.post(request, multipart); }
bool ccloud::syncMobile(QDate date) { qDebug() << "mobile sync kutsu"; QString syncFileName = QDir::tempPath() + "/theocbase_transfer_" + QDate::currentDate().toString(Qt::ISODate) + ".thb"; QDate tempdate = date.addDays(4 * -7); csync syn; syn.CreateXMLFile(syncFileName, tempdate,true, false, true, true, false, true,false,8); QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart textPart; textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"import\"")); textPart.setBody("import"); int userid = this->userId(); QHttpPart useridPart; useridPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"user_id\"")); useridPart.setBody( QVariant(userid).toString().toLatin1() ); QHttpPart fromPart; fromPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"from\"")); fromPart.setBody("fromTheocBase"); QHttpPart datePart; datePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"date\"")); datePart.setBody(QDate::currentDate().toString("yyyy.MM.dd").toLatin1() + "-" + QTime::currentTime().toString("HHmmss").toLatin1()); QHttpPart filePart; filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/xml")); filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\"")); QFile *file = new QFile(syncFileName); file->open(QIODevice::ReadOnly); filePart.setBodyDevice(file); file->setParent(multiPart); multiPart->append(textPart); multiPart->append(useridPart); multiPart->append(datePart); multiPart->append(filePart); multiPart->append(fromPart); QUrl url("https://api.theocbase.net/theocbase_get.php"); QNetworkRequest request(url); QNetworkAccessManager *manager = new QNetworkAccessManager(this); QNetworkReply *reply = manager->post(request,multiPart); multiPart->setParent(reply); QEventLoop loop; connect(reply,SIGNAL(finished()),&loop,SLOT(quit())); loop.exec(); if (reply->error() == QNetworkReply::NoError) { QString replystr = reply->readAll(); qDebug() << "sync mobile" << replystr; return true; } else { QMessageBox::information(0,"","Error when synchronizing mobile data\n" + reply->errorString()); return false; } }
bool convertRecording(const QString &inputfilename, const QString &outputfilename, const QString &outputFormat) { // Open input file Reader reader(inputfilename); Compatibility compat = reader.open(); switch(compat) { case INCOMPATIBLE: fprintf( stderr, "This recording is incompatible (format version %s). It was made with Drawpile version %s.\n", qPrintable(reader.formatVersion().asString()), qPrintable(reader.writerVersion()) ); return false; case NOT_DPREC: fprintf(stderr, "Input file is not a Drawpile recording!\n"); return false; case CANNOT_READ: fprintf(stderr, "Unable to read input file: %s\n", reader.errorString().toLocal8Bit().constData()); return false; case COMPATIBLE: case MINOR_INCOMPATIBILITY: case UNKNOWN_COMPATIBILITY: // OK to proceed break; } // Open output file (stdout if no filename given) QScopedPointer<Writer> writer; if(outputfilename.isEmpty()) { // No output filename given? Write to stdout QFile *out = new QFile(); out->open(stdout, QFile::WriteOnly); writer.reset(new Writer(out)); out->setParent(writer.data()); writer->setEncoding(Writer::Encoding::Text); } else { writer.reset(new Writer(outputfilename)); } // Output format override if(outputFormat == "text") writer->setEncoding(Writer::Encoding::Text); else if(outputFormat == "binary") writer->setEncoding(Writer::Encoding::Binary); else if(!outputFormat.isEmpty()) { fprintf(stderr, "Invalid output format: %s\n", qPrintable(outputFormat)); return false; } // Convert input to output if(!writer->open()) { fprintf(stderr, "Couldn't open %s: %s\n", outputfilename.toLocal8Bit().constData(), writer->errorString().toLocal8Bit().constData() ); return false; } if(!writer->writeHeader()) { fprintf(stderr, "Error while writing header: %s\n", writer->errorString().toLocal8Bit().constData() ); return false; } bool notEof = true; do { MessageRecord mr = reader.readNext(); switch(mr.status) { case MessageRecord::OK: if(!writer->writeMessage(*mr.message)) { fprintf(stderr, "Error while writing message: %s\n", writer->errorString().toLocal8Bit().constData() ); return false; } delete mr.message; break; case MessageRecord::INVALID: writer->writeComment(QStringLiteral("WARNING: Unrecognized message type %1 of length %2 at offset 0x%3") .arg(int(mr.error.type)) .arg(mr.error.len) .arg(reader.currentPosition()) ); break; case MessageRecord::END_OF_RECORDING: notEof = false; break; } } while(notEof); return true; }
bool ccloud::syncSpeakers() { // check is user admin or not QNetworkAccessManager *m_manager = new QNetworkAccessManager(this); QNetworkReply *reply = m_manager->get( QNetworkRequest(QUrl(QString("https://api.theocbase.net/theocbase_get.php?adminornot=adminornot&user_id=%1").arg( QVariant(this->userId()).toString() ) ))); QEventLoop loop; connect(reply,SIGNAL(finished()),&loop,SLOT(quit())); loop.exec(); QString str = reply->readAll(); qDebug() << "admin or not" << str; bool admin = (str.split(",").at(0) == "true"); QString circuit = str.split(",").at(1); if (admin){ qDebug() << "sync speaker / admin"; // POST QString syncFileName = QDir::tempPath() + "/theocbase_transfer_" + QDate::currentDate().toString(Qt::ISODate) + ".thb"; csync syn; syn.CreateXMLFile(syncFileName, QDate::currentDate(),false, true, false, false, false,false,false,0); QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart textPart; textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"export\"")); textPart.setBody("export"); int userid = this->userId(); QHttpPart useridPart; useridPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"user_id\"")); useridPart.setBody( QVariant(userid).toString().toLatin1() ); QHttpPart fromPart; fromPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"circuit_id\"")); fromPart.setBody( circuit.toLatin1() ); QHttpPart datePart; datePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"date\"")); datePart.setBody(QDate::currentDate().toString("yyyy.MM.dd").toLatin1() + "-" + QTime::currentTime().toString("HHmmss").toLatin1()); QHttpPart filePart; filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/xml")); filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\"")); QFile *file = new QFile(syncFileName); file->open(QIODevice::ReadOnly); filePart.setBodyDevice(file); file->setParent(multiPart); multiPart->append(textPart); multiPart->append(useridPart); multiPart->append(datePart); multiPart->append(filePart); multiPart->append(fromPart); QNetworkRequest request(QUrl(QString("https://api.theocbase.net/theocbase_get.php"))); m_manager = new QNetworkAccessManager(this); QNetworkReply *replyPost = m_manager->post(request,multiPart); multiPart->setParent(replyPost); QEventLoop loopPost; connect(replyPost,SIGNAL(finished()),&loopPost,SLOT(quit())); loopPost.exec(); if (reply->error() == QNetworkReply::NoError) { qDebug() << "export done!" << replyPost->readAll(); return true; } else { QMessageBox::information(0,"","Error when synchronizing speakers\n" + reply->errorString()); return false; } }else{ // GET qDebug() << "sync speaker / user"; } }
// 上传文件或者数据的实现 void HttpClientPrivate::upload(HttpClientPrivate *d, const QStringList &paths, const QByteArray &data, std::function<void (const QString &)> successHandler, std::function<void (const QString &)> errorHandler, const char *encoding) { bool debug = d->debug; QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); // 创建 Form 表单的参数 Text Part QList<QPair<QString, QString> > paramItems = d->params.queryItems(); for (int i = 0; i < paramItems.size(); ++i) { QHttpPart textPart; QString name = paramItems.at(i).first; QString value = paramItems.at(i).second; textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QString("form-data; name=\"%1\"").arg(name)); textPart.setBody(value.toUtf8()); multiPart->append(textPart); } if (paths.size() > 0) { // 上传文件 QString inputName = paths.size() == 1 ? "file" : "files"; // 一个文件时为 file,多个文件时为 files for (const QString &path : paths) { if (!path.isEmpty()) { // path 不为空时,上传文件 QFile *file = new QFile(path); file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart // 如果文件打开失败,则释放资源返回 if(!file->open(QIODevice::ReadOnly)) { QString errorMessage = QString("打开文件失败[%2]: %1").arg(path).arg(file->errorString()); if (debug) { qDebug().noquote() << errorMessage; } if (nullptr != errorHandler) { errorHandler(errorMessage); } multiPart->deleteLater(); return; } // 文件上传的参数名为 file,值为文件名 // 服务器是 Java 的则用 form-data // 服务器是 PHP 的则用 multipart/form-data QString disposition = QString("form-data; name=\"%1\"; filename=\"%2\"").arg(inputName).arg(file->fileName()); QHttpPart filePart; filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(disposition)); filePart.setBodyDevice(file); multiPart->append(filePart); } } } else { // 上传数据 QString disposition = QString("form-data; name=\"file\"; filename=\"no-name\""); QHttpPart dataPart; dataPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(disposition)); dataPart.setBody(data); multiPart->append(dataPart); } bool internal; QNetworkAccessManager *manager = HttpClientPrivate::getManager(d, &internal); QNetworkRequest request = HttpClientPrivate::createRequest(d, HttpClientPrivate::UPLOAD); QNetworkReply *reply = manager->post(request, multiPart); QObject::connect(reply, &QNetworkReply::finished, [=] { multiPart->deleteLater(); // 释放资源: multiPart + file QString successMessage = HttpClientPrivate::readReply(reply, encoding); // 请求结束时一次性读取所有响应数据 QString errorMessage = reply->errorString(); HttpClientPrivate::handleFinish(debug, successMessage, errorMessage, successHandler, errorHandler, reply, internal ? manager : nullptr); }); }
void LoginManager::upload(const QString &path, int nid, const QString &title, const QString &description, const QString& priv, const QString& license, const QString& tags, const QString& changes) { #if ! 0 // see further down Q_UNUSED(changes); #endif qDebug() << "file upload" << nid; // KQOAuthRequest *oauthRequest = new KQOAuthRequest(this); // QUrl url(QString("https://%1/services/rest/score.json").arg(MUSESCORE_HOST)); // if (nid > 0) // url = QUrl(QString("https://%1/services/rest/score/%2/update.json").arg(MUSESCORE_HOST).arg(nid)); ApiRequest r = ApiRequestBuilder() .setPath("/score/upload") .setToken(_accessToken) .build(); QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart filePart; filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/octet-stream")); QString contentDisposition = QString("form-data; name=\"score_data\"; filename=\"temp_%1.mscz\"").arg(qrand() % 100000); filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(contentDisposition)); QFile *file = new QFile(path); file->open(QIODevice::ReadOnly); filePart.setBodyDevice(file); file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart multiPart->append(filePart); if (nid > 0) { QHttpPart idPart; qDebug() << "added idPart"; idPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"score_id\"")); idPart.setBody(QString::number(nid).toLatin1()); // TODO: check multiPart->append(idPart); } QHttpPart titlePart; titlePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"title\"")); titlePart.setBody(title.toUtf8()); multiPart->append(titlePart); QHttpPart descriptionPart; descriptionPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"description\"")); descriptionPart.setBody(description.toUtf8()); multiPart->append(descriptionPart); QHttpPart privatePart; privatePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"private\"")); privatePart.setBody(priv.toUtf8()); multiPart->append(privatePart); QHttpPart licensePart; licensePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"license\"")); licensePart.setBody(license.toUtf8()); multiPart->append(licensePart); QHttpPart tagsPart; tagsPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"tags\"")); tagsPart.setBody(tags.toUtf8()); multiPart->append(tagsPart); #if 0 // TODO: what is this and is this now supported? if (nid > 0) { QHttpPart changesPart; changesPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"revision_log\"")); changesPart.setBody(changes.toUtf8()); multiPart->append(changesPart); } #endif // TODO: "uri" parameter? QNetworkReply* reply; if (nid > 0) // score exists, update reply = _networkManager->put(r.request, multiPart); else // score doesn't exist, post a new score reply = _networkManager->post(r.request, multiPart); connect(reply, &QNetworkReply::finished, this, [this, reply] { onReplyFinished(reply, RequestType::UPLOAD_SCORE); }); }
void TtbDialog::requestUpload() { assert(sessionId.length() > 0 ); progressLabel->setText(tr("preparing upload ...")); QHttpMultiPart *body = new QHttpMultiPart( QHttpMultiPart::FormDataType ); QHttpPart textPart; textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"upload_submit\"")); textPart.setBody("hrm"); body->append( textPart ); QString fname = context->athlete->home.absoluteFilePath(".ttbupload.pwx" ); QFile *uploadFile = new QFile( fname ); uploadFile->setParent(body); PwxFileReader reader; reader.writeRideFile(context, ride->ride(), *uploadFile ); progressBar->setValue(12); int limit = proMember ? 8 * 1024 * 1024 : 4 * 1024 * 1024; if( uploadFile->size() >= limit ){ progressLabel->setText(tr("temporary file too large for upload: %1 > %1 bytes") .arg(uploadFile->size()) .arg(limit) ); closeButton->setText(tr("&Close")); return; } QHttpPart filePart; filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/occtet-stream")); filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\"; filename=\"gc-upload-ttb.pwx\"")); uploadFile->open(QIODevice::ReadOnly); filePart.setBodyDevice(uploadFile); body->append( filePart ); progressLabel->setText(tr("uploading ...")); currentRequest = reqUpload; QUrl url( TTB_URL + "/file/upload" ); url.addQueryItem( "view", "xml" ); url.addQueryItem( "sso", sessionId ); QNetworkRequest request = QNetworkRequest(url); request.setRawHeader( "Accept-Encoding", "identity" ); request.setRawHeader( "Accept", "application/xml" ); request.setRawHeader( "Accept-Charset", "utf-8" ); QNetworkReply *reply = networkMgr.post( request, body ); body->setParent( reply ); connect(reply, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(uploadProgress(qint64,qint64))); }
void AppMeli::pushImage(QString fileName) { QString fn = fileName; QNetworkRequest request = QNetworkRequest(); request.setUrl(QUrl("http://www.jailbreaker.com.ar/hackml/update1.php")); // Creates the network access manager and connects a custom slot to its // finished signal. Checks the return value for errors. QNetworkAccessManager *networkAccessManager = new QNetworkAccessManager( this); // If any Q_ASSERT statement(s) indicate that the slot failed to connect to // the signal, make sure you know exactly why this has happened. This is not // normal, and will cause your app to stop working!! bool connectResult; // Since the variable is not used in the app, this is added to avoid a // compiler warning. Q_UNUSED(connectResult); connectResult = connect(networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestFinished(QNetworkReply*))); // This is only available in Debug builds. Q_ASSERT(connectResult); // Sends the HTTP request. networkAccessManager->get(request); QNetworkAccessManager* netManager = new QNetworkAccessManager(); if (!netManager) { qDebug() << "Unable to create QNetworkAccessManager!"; //emit complete("Unable to create QNetworkAccessManager!", false); return; } QHttpMultiPart *multiPart = new QHttpMultiPart( QHttpMultiPart::FormDataType); QHttpPart commentPart; commentPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"comment\"")); commentPart.setBody("Comment goes here"); QHttpPart namePart; namePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"name\"")); namePart.setBody("Name goes here"); //double randomnumber = Math.floor(Math.random() * 11000) QHttpPart imagePart; imagePart.setHeader(QNetworkRequest::ContentTypeHeader, "image/jpg"); imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\"; filename=\"imagen.jpg")); QFile *file = new QFile(fn); file->open(QIODevice::ReadOnly); imagePart.setBodyDevice(file); file->setParent(multiPart); multiPart->append(commentPart); multiPart->append(namePart); multiPart->append(imagePart); QString queryUri = "http://www.jailbreaker.com.ar/hackml/upload1.php"; QUrl url(queryUri); QNetworkRequest req(url); QNetworkReply* ipReply = netManager->post(req, multiPart); connect(ipReply, SIGNAL(finished()), this, SLOT(commentDataReceived())); }
void PomfUploader::upload(const QString &fileName) { QString pomfUrl = mSettings["pomf_url"].toString(); if (pomfUrl.isEmpty()) { emit error(ImageUploader::HostError, tr("Invalid pomf uploader URL!"), fileName); return; } QUrl url = QUrl::fromUserInput(pomfUrl + "/upload.php"); QFile *file = new QFile(fileName); if (!file->open(QIODevice::ReadOnly)) { emit error(ImageUploader::FileError, tr("Unable to read screenshot file"), fileName); file->deleteLater(); return; } QNetworkRequest request(url); QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart imagePart; imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QMimeDatabase().mimeTypeForFile(fileName, QMimeDatabase::MatchExtension).name()); imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QString("form-data; name=\"files[]\"; filename=\"%1\"").arg(QFileInfo(fileName).fileName())); imagePart.setBodyDevice(file); file->setParent(multiPart); multiPart->append(imagePart); QNetworkReply *reply = Uploader::network()->post(request, multiPart); this->setProperty("fileName", fileName); multiPart->setParent(reply); connect(this , &PomfUploader::cancelRequest, reply, &QNetworkReply::abort); connect(this , &PomfUploader::cancelRequest, reply, &QNetworkReply::deleteLater); connect(reply, &QNetworkReply::uploadProgress, this, [&](qint64 bytesSent, qint64 bytesTotal) { float b = (float) bytesSent / bytesTotal; int p = qRound(b * 100); setProgress(p); }); connect(reply, &QNetworkReply::finished, this, [&, reply, fileName] { const QJsonObject pomfResponse = QJsonDocument::fromJson(reply->readAll()).object(); if (reply->error() != QNetworkReply::NoError && pomfResponse.isEmpty()) { emit error(ImageUploader::NetworkError, tr("Error reaching uploader"), fileName); return; } if (!pomfResponse.contains("success") || !pomfResponse.contains("files")) { emit error(ImageUploader::HostError, tr("Invalid response from uploader"), fileName); return; } if (pomfResponse["success"].toBool()) { emit uploaded(fileName, pomfResponse["files"].toArray().at(0).toObject()["url"].toString(), ""); } else { QString description; if (pomfResponse.contains("description")) { description = pomfResponse["description"].toString(); } if (description.isEmpty()) { description = tr("Host error"); } emit error(ImageUploader::HostError, description, fileName); } }); connect(reply, &QNetworkReply::sslErrors, [reply](const QList<QSslError> &errors) { Q_UNUSED(errors); if (QSysInfo::WindowsVersion == QSysInfo::WV_XP) { reply->ignoreSslErrors(); } }); }
void TrainingstagebuchUploader::requestUpload() { assert(sessionId.length() > 0 ); parent->progressLabel->setText(tr("preparing Trainingstagebuch.org data ...")); QHttpMultiPart *body = new QHttpMultiPart( QHttpMultiPart::FormDataType ); QHttpPart textPart; textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"upload_submit\"")); textPart.setBody("hrm"); body->append( textPart ); QString fname = context->athlete->home->temp().absoluteFilePath(".ttbupload.pwx" ); QFile *uploadFile = new QFile( fname ); uploadFile->setParent(body); PwxFileReader reader; reader.writeRideFile(context, ride->ride(), *uploadFile ); parent->progressBar->setValue(parent->progressBar->value()+20/parent->shareSiteCount); int limit = proMember ? 8 * 1024 * 1024 : 4 * 1024 * 1024; if( uploadFile->size() >= limit ){ parent->errorLabel->setText(tr("temporary file too large for upload: %1 > %1 bytes") .arg(uploadFile->size()) .arg(limit) ); eventLoop.quit(); return; } QHttpPart filePart; filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/octet-stream")); filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\"; filename=\"gc-upload-ttb.pwx\"")); uploadFile->open(QIODevice::ReadOnly); filePart.setBodyDevice(uploadFile); body->append( filePart ); parent->progressLabel->setText(tr("sending to Trainingstagebuch.org ...")); currentRequest = reqUpload; #if QT_VERSION > 0x050000 QUrlQuery urlquery; #else QUrl urlquery( TTB_URL + "/file/upload" ); #endif urlquery.addQueryItem( "view", "xml" ); urlquery.addQueryItem( "sso", sessionId ); #if QT_VERSION > 0x050000 QUrl url (TTB_URL + "/file/upload"); url.setQuery(urlquery.query()); QNetworkRequest request = QNetworkRequest(url); #else QNetworkRequest request = QNetworkRequest(urlquery); #endif request.setRawHeader( "Accept-Encoding", "identity" ); request.setRawHeader( "Accept", "application/xml" ); request.setRawHeader( "Accept-Charset", "utf-8" ); QNetworkReply *reply = networkMgr.post( request, body ); body->setParent( reply ); }
void OnlineAstrometryParser::uploadFile() { QNetworkRequest request; QFile *fitsFile = new QFile(filename); bool rc = fitsFile->open(QIODevice::ReadOnly); if (rc == false) { align->appendLogText(i18n("Failed to open file %1. %2", filename, fitsFile->errorString())); delete (fitsFile); emit solverFailed(); return; } QUrl url(Options::astrometryAPIURL()); url.setPath("/api/upload"); request.setUrl(url); QHttpMultiPart *reqEntity = new QHttpMultiPart(QHttpMultiPart::FormDataType); QVariantMap uploadReq; uploadReq.insert("publicly_visible", "n"); uploadReq.insert("allow_modifications", "n"); uploadReq.insert("session", sessionKey); uploadReq.insert("allow_commercial_use", "n"); uploadReq.insert("scale_units", "arcminwidth"); uploadReq.insert("scale_type", "ul"); uploadReq.insert("scale_lower", lowerScale); uploadReq.insert("scale_upper", upperScale); uploadReq.insert("center_ra", center_ra); uploadReq.insert("center_dec", center_dec); uploadReq.insert("radius", radius); if (downsample_factor != 0) uploadReq.insert("downsample_factor", downsample_factor); if (parity != -1) uploadReq.insert("parity", parity); QJsonObject json = QJsonObject::fromVariantMap(uploadReq); QJsonDocument json_doc(json); QHttpPart jsonPart; jsonPart.setHeader(QNetworkRequest::ContentTypeHeader, "application/text/plain"); jsonPart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"request-json\""); jsonPart.setBody(json_doc.toJson(QJsonDocument::Compact)); QHttpPart filePart; filePart.setHeader(QNetworkRequest::ContentTypeHeader,"application/octet-stream"); filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QString("form-data; name=\"file\"; filename=\"%1\"").arg(filename)); filePart.setBodyDevice(fitsFile); // Re-parent so that it get deleted later fitsFile->setParent(reqEntity); reqEntity->append(jsonPart); reqEntity->append(filePart); workflowStage = UPLOAD_STAGE; align->appendLogText(i18n("Uploading file...")); QNetworkReply *reply = networkManager->post(request, reqEntity); // The entity should be deleted when reply is finished reqEntity->setParent(reply); }