qtcurlbox-apiqtnetwork

How to upload files to box? I have curl code


I am integrating box cloud in my application. I am working with Qt platform.

In box documentation, they said to post like this which is in curl.

curl https://upload.box.com/api/2.0/files/content \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-F filename=@FILE_NAME \
-F folder_id=FOLDER_ID 

where to specify the filename and folder_id parameters. I have tried by posting in the body but it is giving error. And also please tell me where to post the file contents.

Thanks.


Solution

  • I tried by posting with multipart/form-data using the Qt API. I am not familiar with using libcurl in Qt. But I got success with Qt API only. Here is my code.

    multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    
            QByteArray boundary("56354654654654321768987465413574634354658");
            multiPart->setBoundary(boundary);
    
            QHttpPart folderPart;
            folderPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"folder_id\""));
            folderPart.setBody(folderId.toUtf8());
    
            QString fileExt = fileToUpload.split(".").takeLast();
            QString mimeType = FileUtilities::getMIMEType("." + fileExt);
    
            QString fileName = fileToUpload.split("/").takeLast();
            qDebug() << "file name to upload : " << fileName;
    
            QHttpPart textPart;
            textPart.setHeader(QNetworkRequest::ContentTypeHeader, mimeType);
            textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; filename=\""+ fileName +"\"; name=\"filename\";"));
    
            QFile *fileUpload = new QFile(fileToUpload);
            fileUpload->open(QIODevice::ReadOnly);
    
            textPart.setBodyDevice(fileUpload);
    
            multiPart->append(textPart);
            multiPart->append(folderPart);
    req.setUrl(QUrl("https://upload.box.com/api/2.0/files/content"));
    QByteArray ba_auth = QString("Bearer " + m_accessToken).toUtf8();
    req.setRawHeader("Authorization", ba_auth);
    
    
    m_netManager->post(req, multiPart);
    

    And the reply will be the details of the file that has been uploaded to box.com. Thanks everybody for helping me in this topic.