首页 技术 正文
技术 2022年11月15日
0 收藏 526 点赞 4,184 浏览 4117 个字

最近在做一个项目,需要与WEB服务器交互一些信息。其中一项就是文件的上传与下载。现来一个上传的代码

#include "stdio.h"
#include "WinSock2.h"
#include "iostream"
using namespace std;
#pragma comment(lib,"ws2_32.lib")
long l_file_len;
//获取文件内容
bool file_con(char **buffer,LPCSTR file)
{
FILE *fp = fopen(file, "rb");
if(fp==NULL)
{
printf("文件上传失败,请检查文件路径.....\n");
return false;
}
fseek(fp, , SEEK_END);
l_file_len = ftell(fp);
rewind(fp); *buffer = new char[l_file_len + ];
memset(*buffer, , l_file_len + );
fseek(fp, , SEEK_SET);
fread(*buffer, sizeof(char), l_file_len, fp);
fclose(fp);
return true;
} //文件上传
std::string upload(LPCSTR lpszServer,LPCSTR lpszAddr,LPCSTR fileUrl)
{
char *file = NULL;
if(!file_con(&file,fileUrl))
{
return "";
}
SOCKET sock = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_SOCKET)
return "";
SOCKADDR_IN server;
server.sin_family = AF_INET;
server.sin_port = htons();
struct hostent *host_addr = gethostbyname(lpszServer);
if (host_addr == NULL)
return "host_addr == NULL";
server.sin_addr.s_addr = *((int *) *host_addr->h_addr_list);
if (::connect(sock, (SOCKADDR *) &server, sizeof(SOCKADDR_IN)) == SOCKET_ERROR)
{
::closesocket(sock);
return "";
}
printf("ip address = %s, port = %d\n",inet_ntoa(server.sin_addr), ntohs(server.sin_port)); std::string header("");
std::string content("");
//----------------------post头开始--------------------------------
header +="post ";
header +=lpszAddr;
header +=" HTTP/1.1\r\n";
header +="Host: ";
header +=lpszServer;
header += "\r\n";
header += "User-Agent: Mozilla/4.0\r\n";
header += "Connection: Keep-Alive\r\n";
header += "Accept: */*\r\n";
header += "Pragma: no-cache\r\n";
header += "Content-Type: multipart/form-data; charset=\"gb2312\"; boundary=----------------------------64b23e4066ed\r\n"; content += "------------------------------64b23e4066ed\r\n";
content += "Content-Disposition: form-data; name=\"file\"; filename=\"大论文和实验材料.rar\"\r\n";
content += "Content-Type: aapplication/octet-stream\r\n\r\n"; //post尾时间戳
std::string strContent("\r\n------------------------------64b23e4066ed\r\n");
char temp[] = {};
//注意下面这个参数Content-Length,这个参数值是:http请求头长度+请求尾长度+文件总长度
sprintf(temp, "Content-Length: %d\r\n\r\n", content.length()+l_file_len+strContent.length());
header += temp;
std::string str_http_request;
str_http_request.append(header).append(content);
//----------------------post头结束-----------------------------------
//发送post头
send(sock, str_http_request.c_str(), str_http_request.length(), ); char fBuff[];
int nPacketBufferSize = ; // 每个数据包存放文件的buffer大小
int nStart;//记录post初始位置
int nSize;//记录剩余文件大小
// 就分块传送
for (int i = ; i < l_file_len; i += nPacketBufferSize)
{
nStart=i;
if (i + nPacketBufferSize + > l_file_len)
{
nSize = l_file_len - i;
}
else
{
nSize = nPacketBufferSize;
} memcpy(fBuff, file + nStart, nSize);
::send(sock, fBuff, nSize, );
Sleep(0.2);
} ::send(sock,strContent.c_str(),strContent.length(),); char szBuffer[] = {};
while (true)
{ int nRet = ::recv(sock, szBuffer, sizeof(szBuffer), );
if (nRet == || nRet == WSAECONNRESET)
{
printf("Connection Closed.\n");
break;
}
else if (nRet == SOCKET_ERROR)
{
printf("socket error\n");
break;
}
else
{
printf("recv() returned %d bytes\n", nRet);
printf("received: %s\n", szBuffer);
break;
}
}
::closesocket(sock);
delete [] file;
return szBuffer;
}
void main()
{
WORD wVersionRequested=MAKEWORD(,);
WSADATA wsaData;
if(WSAStartup(wVersionRequested,&wsaData))
{
cout<<"加载错误"<<endl;
}
if(LOBYTE(wsaData.wVersion)!=||HIBYTE(wsaData.wHighVersion)!=)
{
cout<<"WinSock's 加载错误"<<endl;
}
upload("localhost","/WebApplication1/Default.aspx","F:\\postgresql-8.3.3-2.rar");
}

这是上传文件的C++代码

下面是用 asp.net写的服务端的接收数据的代码

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text; namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Files.Count > 0)
{
try
{
HttpPostedFile file = Request.Files[0];
string filePath = Request.PhysicalApplicationPath + file.FileName;
file.SaveAs(filePath);
Response.Write("Success\r\n");
}
catch
{
Response.Write("Error\r\n");
}
Response.End();
}
}
}
} 上面就是简单的代码示例,web需配置iis,相信大家知道怎么做^_^,还有一点就是web程序默认上传文件的限制,默认上传大小为4M,所以需要
在web.config中设置以下参数:
[html] view plaincopy
<httpRuntime maxRequestLength="951200" appRequestQueueLimit="60" executionTimeout="60"/>

  

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,078
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,553
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,402
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,177
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,814
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898