Upload and download files on the Http server (5 ),

Source: Internet
Author: User

Upload and download files on the Http server (5 ),

I. Introduction

You are welcome to compile an Http server with me to upload and download files. Now I will review some of the content mentioned in the previous chapter. I have mentioned File Download before, as mentioned in the file downloading, you only need to enter the Content-Range field in the response header, and the server's file Pointer Points to the specified read location to start reading and transmitting files. In this chapter, I will explain the file upload function. After this chapter is completed, all the general functions are completed, followed by the above file control module and some resource modules.

The HttpRequest class is mainly used for file uploads. I am confused when considering file uploads. whether to put the file upload function under HttpResponse or HttpRequest is true, after all, HttpResponse has some corresponding file download functions, and it is no longer necessary to add a file upload function. But I finally chose HttpRequest because I mainly use HttpResponse as the server to send content to the browser, and HttpRequest as the browser to send content to the server. In this way, the download and upload functions are located on HttpResponse and HttpRequest respectively.

After the ownership of the function is completed, you can directly upload the code, which involves the C ++ stream during file upload. Not a lot of content is actually used here, but it is an important part of C ++. Have time to review this part with everyone. Now let's go to the code. The content in the previous chapter includes some HttpRequest code, not all of which are included.

Ii. HttpRequest

Header file (include/httprequest. h)

 1 #ifndef HTTPREQUEST_H 2 #define HTTPREQUEST_H 3 #include "socket.h" 4 #include <map> 5 #include <string> 6 #include <fstream> 7 namespace Http{ 8     class HttpRequest{ 9         public:10             HttpRequest(TCP::Socket &c);11             virtual ~HttpRequest();12             std::string getMethod() const;13             std::string getUrl()  const;14             std::string getHost() const;15             std::map<std::string,std::string>  getHeader(int confd) ;16             ssize_t upload(int confd,std::string filename);17         protected:18         private:19             std::string method;20             std::string url;21             std::string host;22             TCP::Socket &s;23     };24 }25 #endif // HTTPREQUEST_H

Source file (src/httprequest. cpp)

 1 #include "httprequest.h" 2 #include "utils.h" 3 namespace Http{ 4     HttpRequest::HttpRequest(TCP::Socket &c):s(c){ 5     } 6  7     HttpRequest::~HttpRequest(){ 8     } 9     std::map<std::string,std::string> HttpRequest::getHeader(int confd){10         char recvBuf[1024];11         memset(recvBuf,0,sizeof(recvBuf));12         s.server_read(confd,recvBuf,1024);13         std::cout<<recvBuf<<std::endl;14         std::map<std::string,std::string> mp =Utils::parseHeader(recvBuf);15         method =mp["Method"];16         url=mp["Url"];17         host=mp["Host"];18         return mp;19     }20     ssize_t HttpRequest::upload(int confd,std::string filename){21         char buf[1024];22         size_t n=0;23         ssize_t  nread=0;24         std::string boundary;25         std::string file;26         std::ofstream outStream;27         int readlineCount=1;28         while(1){29             memset(buf,0,sizeof(buf));30             n=s.server_readline(confd,buf,sizeof(buf));31             if(readlineCount==1){32                 boundary=std::string(buf,buf+strlen(buf)-2);33                 boundary+="--\r\n";34                 std::cout<<boundary<<std::endl<<boundary.size();35             }else if(readlineCount==2){36                 int i=n;37                 while(buf[i]!='='){38                     if((buf[i]>='0'&&buf[i]<='9')39                        ||(buf[i]>='a'&&buf[i]<='z')40                        ||(buf[i]>='A'&&buf[i]<='Z')41                        ||(buf[i]=='.'))42                     i--;43                     else{44                         buf[i]='*';45                         i--;46                     }47                 }48                 file=std::string(buf+i+2,buf+n-3);49             }else if(readlineCount==3){50                 std::string rw;51                 rw=std::string(buf,buf+strlen(buf));52                 int pos=rw.find('/');53                 rw=rw.substr(0,pos);54                 filename=filename+file;55                 if(rw=="Content-Type: text")56                     outStream.open(filename.c_str());57                 else{58                     outStream.open(filename.c_str(),std::ios::binary);59                     std::cout<<"ios::binary"<<std::endl;60                 }61             }else if(readlineCount==4){62                 memset(buf,0,sizeof(buf));63                 while(1){64                     n=s.server_readn(confd,buf,sizeof(buf));65                     if(n==boundary.size()&&strcmp(buf,boundary.c_str())==0){66                         goto exit;67                     }68                     nread+=n;69                     if(buf[n-1]==0){70                         outStream.write(buf,n-1);71                     }else{72                       outStream.write(buf,n);73                     }74                 }75             }76             readlineCount++;77         }78         exit:79         outStream.close();80         s.server_close(confd);81         return nread;82     }83     std::string HttpRequest::getMethod() const{84         return method;85     }86     std::string HttpRequest::getUrl()  const{87         return url;88     }89     std::string HttpRequest::getHost() const{90         return host;91     }92 }

The code for uploading files has also come out. Now I want to explain it a little bit. Before the Code is interpreted, when we press the file upload button, the browser sends the content to the server. For example, if I have a text file test.txt (the file is used to view the content, the binary file is consistent ). The test.txt file contains only one row of the six letters aaabbb. Then open the developer network that can be Firefox. After clicking send file, you can see the following information in the message header.

These contents have already been discussed in the previous chapter, so we will not repeat them here, and click the parameter option to see the following information.

Here, line 1 and 2 are the content of the request header, followed by line 4-9 of the Request body after a blank line. The content of the request is not directly test.txt. It starts with '-- 23469111452', and the reader is a text separator. The preceding fixed segment '-' is added with the data automatically generated by a browser. This is also the interpretation of a file, but there are two more '-' after the number '-'. Lines 5 and 6 describe the uploaded file. Then there is a blank line. The first line is the file content. After knowing this request body, you can easily write code. In the above upload, The readlineCount variable is used for locating. Check that the server has received that line. The number of s. server_readn lines is not submitted, and the current code segment has been being modified. Therefore, some of them are slightly different from those of the blog, which is basically the same.

Here, the file upload and download functions of HttpServer are basically completed. Then combine these blocks. The following section describes how to upload and download files on the Http server (6.

 

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.