qt uploads files via HTTP Post

Source: Internet
Author: User
Tags http post django server

This article uses QT creator to upload files using the HTTP POST method, and gives an example of uploading files.

This article is the main client, so the description of the server-side programming will be relatively brief

The server uses Django to write, the method that the Django server receives the file has the clear explanation in the article http://www.cnblogs.com/fnng/p/3740274.html, The server-side program I built is basically the same as the server setup of this article, except that there are no Web clients and some variable names.

If the server-side program changes, the client routines given later in this article may no longer be applicable. Therefore, if you run the client program and find that the server side cannot receive the file, do not directly consider the client routine given by this article to be wrong, or it may be caused by other problems.

I did not attempt to upload large files, upload multiple files at the same time, and include Chinese in the file name in three cases when I was making the program. Therefore, in these three cases, the program is likely to appear bug.

Sample program Links: Http://pan.baidu.com/s/1i5NWsHR

1. Server-side

Server-side Program basic Reference http://www.cnblogs.com/fnng/p/3740274.html. The code is posted directly here, the construction process and the code description are not explained.

disk/views.py:

From django.shortcuts import Render,render_to_response

From django.http import HttpResponse

From Django Import forms

From. Models Import User

Import OS

# Create your views here.

Class UserForm (forms. Form):

Username=forms. Charfield ()

Upload_file=forms. Filefield ()

def index (Request):

If request.method== "POST":

Uf=userform (Request. Post,request. FILES)

Print (str (Request. POST))

Print (str (Request. FILES))

If Uf.is_valid ():

username=uf.cleaned_data[' username ']

upload_file=uf.cleaned_data[' Upload_file ']

Dir_name= './upload/' +username

If Os.path.exists (dir_name) ==false:

Os.mkdir (Dir_name)

User=user ()

User.username=username

User.upload_file=upload_file

User.save ()

return HttpResponse (' Upload ok! ')

Else

Uf=userform ()

Return HttpResponse (' 000! ')

disk/models.py:

From django.db import Models

# Create your models here.

def content_file_name (instance,filename):

s= '/'. Join ([' upload ', instance.username,filename])

return s

Class User (models. Model):

Username=models. Charfield (max_length=30)

Upload_file=models. Filefield (Upload_to=content_file_name)

def __unicode__ (self):

Return Self.username

disk/urls.py:

From Django.conf.urls import URL

From. Import views

urlpatterns=[

#View the information of user.

URL (r ' ^$ ', views.index,name= ' index '),

]

2. Data that the client program should upload

When the client program uploads a file to the server, it cannot upload only the contents of the file. If the uploaded data contains only the contents of the file, the server side is not able to receive the file normally. The content that the client uploads should include the common form data, the file header and the file content three parts, and the data that needs to transmit is normalized to splice, upload the data according to the specific format.

For this server-side program that I made with Django, the client needs to upload a normal data named username and a file with name Upload_file. The following code splices the data that needs to be sent and sends the data to the server using a POST request.

3. Areas to be aware of in the new construction process

In the pro file to add QT + + network if not added will be an error

Add the containing #include to the front of the code file. (The program will fail to compile if not added) I myself learned to use QT for HTTP communication when I found that many articles on the web did not post the previous # include section when I posted the code, which led me to spend a long time looking for files to refer to.

4. The code for the client to upload the file

void Uploadform (QString path,qmap<</span>qstring,qstring> params,qstringfileformname,qfile *uploadFile , QString NewFileName) {

QString Boundary=quuid::createuuid (). toString ();

Qbytearray Sb=qbytearray ();

Upload normal form data first

For (Qmap<</span>qstring,qstring>::iteratort=params.begin (); T!=params.end (); t++) {

Sb.append ("--" +boundary+ "\ r \ n");

Sb.append (QString ("content-disposition:form-data;name=\") +t.key () +qstring ("\" ") +qstring (" \ r \ n "));

Sb.append ("\ r \ n");

Sb.append (T.value () + "\ r \ n");

}

Upload the file header

Sb.append ("--" +boundary+ "\ r \ n");

Sb.append (QString ("content-disposition:form-data;name=\") +fileformname+qstring ("\"; filename=\ "") +newFileName+ QString ("\" ") +qstring (" \ r \ n "));

Sb.append ("\ r \ n");

Upload file contents

if (!uploadfile->open(qiodevice::ReadOnly)) {

Return

}

Sb.append (Uploadfile->readall ());

Sb.append ("\ r \ n");

Sb.append ("--" +boundary+ "\ r \ n");

Edit HTTP Header

Qnetworkaccessmanager *_uploadmanager=new Qnetworkaccessmanager ();

Qnetworkrequest request=qnetworkrequest (Qurl (Path));

Request.setrawheader (QString ("Content-type"). ToLatin1 (), QString ("multipart/form-data;boundary=" +boundary). ToLatin1 ());

Request.setrawheader (QString ("Content-length"). ToLatin1 (), Qstring::number (Sb.length ()). ToLatin1 ());

Perform a POST request

_uploadmanager->post (REQUEST,SB);

}

5. Write the code for the main function call to upload the file before completing the test.

Here, we have submitted a normal form data named Username, which has a value of 10005. We also submitted a file with name Upload_file. We uploaded the local ":/untitled.png" file, after uploading the server will receive this file, save the name of "1a.png"

int main (int argc, char *argv[])

{

Qcoreapplication A (argc, argv);

QString path= "http://192.168.252.2:8000/disk/"; The URL of the server

Qmap<</span>qstring,qstring> Params_send; Upload the common parameters in this program need to upload a common parameter "username"

Params_send.insert ("username", "10005");

QString fileformname= "Upload_file"; Upload the name of the file form

QFile *file=new QFile (":/untitled.png");

QString newfilename= "1a.png";

Uploadform (Path,params_send,fileformname,file,newfilename);

return A.exec ();

}

6. Effects



We're sending this picture "Untitled.png" to the server.

The server received a picture from the client, the form data username=10005, so a new folder "10005", the received picture is saved in this folder and named "1a.png"

7. References

Http://www.cnblogs.com/fnng/p/3740274.html

Https://forum.qt.io/topic/11086/solved-qnetworkaccessmanager-uploading-files

http://blog.csdn.net/lmj623565791/article/details/23781773

If you find a problem welcome to leave a message or private messages I

Http://blog.sina.com.cn/s/blog_15d207b300102xvqz.html

qt uploads files via HTTP Post

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.