I'm trying to upload a "binary" file, eg pdf, xls to the server.

Uploading .txt works ok but am somewhat confused as to how to deal with binary files, ie encoding to string.

Below is the snippet of code I've got at the moment attemping to load an xls

TIA
Pete


   def upload_file(self, params, file_path):
       print "======================= UPLOAD    =============="

file_name = QtCore.QDateTime().currentDateTime().toString("hh_mm_ss") + ".xls"

       fileObj = QtCore.QFile(file_path)
       fileObj.open(QtCore.QIODevice.ReadOnly)

       ### Constants
       CRLF = "\r\n"
       BOUNDARY = "-----------------------------7d935033608e2"
       START_DELIM = "--" + BOUNDARY + CRLF

       ## Byte array to append to
       data = QtCore.QByteArray()

## Add the paramaters as form-data eg {'foo': 'bar', 'bar': 'beer'}, This works OK
       for p_key in params:
st = QtCore.QString(START_DELIM + ('Content-Disposition: form-data; name="%s"' % p_key) + CRLF + CRLF)
           st.append( "%s%s" % (params[p_key], CRLF) )
           data.append( st.toUtf8() ) # should this be utf8 ?

       ## Append the file - binary ## Problem is here
st = QtCore.QString(START_DELIM + 'Content-Disposition: form-data; name="uploaded_file"; filename="%s";%s' % ( file_name, CRLF ))
       st.append("Content-Type: application/octet-stream" + CRLF + CRLF )
       st.append( fileObj.readAll() ) ## Reads the file as binary ??
       st.append( CRLF + "--" + BOUNDARY + "--" + CRLF )
       data.append( st.toUtf8() ) # should this be utf8 ?

       dataToSend = QtCore.QString(data).toAscii()
       print "payload size=", dataToSend.size() #, payload

       ## Constuct Request
       url = QtCore.QUrl(self.settings.upload_url)
       self.request.setUrl( url )
self.request.setRawHeader("Content-Type", 'multipart/form-data; boundary="%s"' % BOUNDARY) self.request.setHeader(QtNetwork.QNetworkRequest.ContentLengthHeader, QtCore.QVariant(dataToSend.size()) )

       ## Post to server
       self.reply = self.netMan.post( self.request, dataToSend )
self.connect(self.reply, QtCore.SIGNAL("uploadProgress(qint64,qint64)"), self.file_upload_progress) self.connect(self.reply, QtCore.SIGNAL("finished()"), self.file_upload_finished)

   def file_upload_progress(self, foo, bar):
       print "prog", foo, bar):

   def file_upload_finished(self):
       print "finished upload"
       print self.reply.readAll()
_______________________________________________
PyQt mailing list    PyQt@riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt

Reply via email to