服务器参数文件,向服务器POST数据(参数+文件),该怎么解决

该博客探讨了一个在向服务器POST数据时遇到的问题,其中包含参数和文件。作者指出,原始代码使用了错误的Content-Type(application/x-www-form-urlencoded),而应该使用multipart/form-data来正确发送包含文件的POST请求。这个问题导致服务器无法接收到文件,但参数能正常传递。解决方案是调整请求头的Content-Type,并遵循multipart/form-data的格式规范来构造请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

向服务器POST数据(参数+文件)

public string PostFile(string FilePath,string user,string codeid, Encoding encoding, ProgressBar p)

{

string strResult = string.Empty;

string param = "userid" + "=" + user + "&" +"code" + "=" + codeid + "&" + "Photo" + "=";

HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(PostUrl);

myRequest.Method = "Post";

myRequest.KeepAlive = true;

myRequest.ContentType = "application/x-www-form-urlencoded";

myRequest.Accept = "*/*";

byte[] PostArray = encoding.GetBytes(param);

FileStream Filestream = new FileInfo(FilePath).OpenRead();

BinaryReader oReader = new BinaryReader(Filestream);

byte[] imgdata = oReader.ReadBytes(Convert.ToInt32(Filestream.Length));

byte[] data = new byte[PostArray.Length + imgdata.Length];

myRequest.ContentLength = PostArray.Length + imgdata.Length;

PostArray.CopyTo(data, 0);

imgdata.CopyTo(data, PostArray.Length);

Stream PostStream = myRequest.GetRequestStream();

PostStream.Write(data, 0, data.Length);

PostStream.Close();

////获取服务器端的响应

WebResponse webRespon;

try

{

webRespon = myRequest.GetResponse();

}

catch (WebException ex)

{

webRespon = (HttpWebResponse)ex.Response;

}

Stream s = webRespon.GetResponseStream();

StreamReader sr = new StreamReader(s);

strResult = sr.ReadLine();

sr.Close();

s.Close();

Filestream.Close();

return strResult;

} 客户端想服务器POST 参数跟文件 文件发不过去用fidder看参数是带值的 但是到了服务器就收不到了  抛去文件 id 跟code可以传过去 求问大神

分享到:

更多

------解决方案--------------------

你看仔细了,那个就是用的"multipart/form-data"而不是你写的"application/x-www-form-urlencoded",参数传递方式大不相同,你网上查下"multipart/form-data"的写法吧。

例如:http://yefeng.iteye.com/blog/315847

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值