c#如何post文件流

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c#如何post文件流相关的知识,希望对你有一定的参考价值。

我是调用其他人的接口碰到了这样的问题。
我是使用HttpWebRequest类进行post发送的,我发送xml字符串的时候是这样的:
string strPost="a="+a+"&b="+strXML;
byte[] data = Encoding.GetEncoding("GBK").GetBytes(strPost);
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentLength = data.Length;
//发送报文
Stream smRequest = httpRequest.GetRequestStream();
smRequest.Write(data, 0, data.Length);
smRequest.Close();

//接收回执报文
Stream smResponse = httpRequest.GetResponse().GetResponseStream();
using (StreamReader responseReader =
new StreamReader(smResponse, Encoding.GetEncoding("GBK")))

strResult = responseReader.ReadToEnd();

smResponse.Close();
这样发送过去对方的接口是可以接受xml的字符串。后来我在做另外一个接口的时候是传递文件流。我看了下对方接受b这个参数的类型是CommonsMultipartFile(JAVA的接口)。也就是我把文件流转换为string字符串传过去那个接口是不接收的。直接报远程服务器返回错误: (500) 内部服务器错误。

所以C#要怎么POST文件流给对方。肯定不能像我上面写的那样string strPost="a="+a+"&b="+FileStream;
注意,a这个参数是string,b参数传递的是file类型。求解

C#中post用法如下:

首先,POST请求会把请求的数据放置在HTTP请求包的包体中。

其次,POST,由于不是URL传值,理论上是不会受限制的,但是实际上各个服务器会规定对POST提交数据大小进行限制,Apache、IIS都有各自的配置。

最后,POST的安全性较高。

通过C#post文件流的如下代码为:

using System;

using System.Collections.Generic;

using System.Collections.Specialized;

using System.IO;using System.Net;

using System.Text;  

public class HttpPost       

/// <summary>    /// 

以Post 形式提交数据到 uri    

/// </summary>    /// 

<param name="uri">

</param>    

/// <param name="files">

</param>    

/// <param name="values"></param>   

/// <returns></returns>    

public static byte[] Post(Uri uri, IEnumerable<UploadFile> files, NameValueCollection values)            

string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");        

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);        

request.ContentType = "multipart/form-data; boundary=" + boundary;        

request.Method = "POST";        

request.KeepAlive = true;        

request.Credentials = CredentialCache.DefaultCredentials;          

MemoryStream stream = new MemoryStream();         

byte[] line = Encoding.ASCII.GetBytes("\\r\\n--" + boundary + "\\r\\n");        

//提交文本字段        

if (values != null)        

            

string format = "\\r\\n--" + boundary + "\\r\\nContent-Disposition: form-data; name=\\"0\\";\\r\\n\\r\\n1";           

foreach (string key in values.Keys)            

                

string s = string.Format(format, key, values[key]);                

byte[] data = Encoding.UTF8.GetBytes(s);                

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

            

stream.Write(line, 0, line.Length);                 

//提交文件        

if (files != null)       

            

string fformat = "Content-Disposition: form-data; name=\\"0\\"; filename=\\"1\\"\\r\\n Content-Type: application/octet-stream\\r\\n\\r\\n";            

foreach (UploadFile file in files)            

                string s = string.Format(fformat, file.Name, file.Filename);                

byte[] data = Encoding.UTF8.GetBytes(s);                

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

stream.Write(file.Data, 0, file.Data.Length);               

stream.Write(line, 0, line.Length);          

                  

request.ContentLength = stream.Length;          

Stream requestStream = request.GetRequestStream();         

stream.Position = 0L;        

stream.CopyTo(requestStream);        

stream.Close();         

requestStream.Close();           

using (var response = request.GetResponse())        

using (var responseStream = response.GetResponseStream())        

using (var mstream = new MemoryStream())        

            responseStream.CopyTo(mstream);            

return mstream.ToArray();                    

/// <summary>    /// 上传文件    

/// </summary>    

public class UploadFile    

        

public UploadFile()        

            

ContentType = "application/octet-stream";                

public string Name get; set;         

public string Filename get; set;         

public string ContentType get; set;         

public byte[] Data get; set;     

参考技术A protected string GetWebContent(string url)

Stream outstream = null;
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
// 要注意的这是这个编码方式,还有内容的Xml内容的编码方式
Encoding encoding = Encoding.GetEncoding("GBK");
byte[] data = encoding.GetBytes(url);

// 准备请求,设置参数
request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
//request.ContentType = "text/plain";
request.ContentLength = data.Length;

outstream = request.GetRequestStream();
outstream.Write(data, 0, data.Length);
outstream.Flush();
outstream.Close();
//发送请求并获取相应回应数据

response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
instream = response.GetResponseStream();
sr = new StreamReader(instream, encoding);
//返回结果网页(html)代码

string content = sr.ReadToEnd();
return content;


Post提交xml
private string PostXml(string url, string strPost)

string result = "";

StreamWriter myWriter = null;

HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
objRequest.ContentType = "text/xml";//提交xml
//objRequest.ContentType = "application/x-www-form-urlencoded";//提交表单
try

myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);

catch (Exception e)

return e.Message;

finally

myWriter.Close();


HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))

result = sr.ReadToEnd();
sr.Close();

return result;
参考技术B using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;

public class HttpPost


/// <summary>
/// 以Post 形式提交数据到 uri
/// </summary>
/// <param name="uri"></param>
/// <param name="files"></param>
/// <param name="values"></param>
/// <returns></returns>
public static byte[] Post(Uri uri, IEnumerable<UploadFile> files, NameValueCollection values)

string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Credentials = CredentialCache.DefaultCredentials;

MemoryStream stream = new MemoryStream();

byte[] line = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

//提交文本字段
if (values != null)

string format = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"0\";\r\n\r\n1";
foreach (string key in values.Keys)

string s = string.Format(format, key, values[key]);
byte[] data = Encoding.UTF8.GetBytes(s);
stream.Write(data, 0, data.Length);

stream.Write(line, 0, line.Length);


//提交文件
if (files != null)

string fformat = "Content-Disposition: form-data; name=\"0\"; filename=\"1\"\r\n Content-Type: application/octet-stream\r\n\r\n";
foreach (UploadFile file in files)

string s = string.Format(fformat, file.Name, file.Filename);
byte[] data = Encoding.UTF8.GetBytes(s);
stream.Write(data, 0, data.Length);

stream.Write(file.Data, 0, file.Data.Length);
stream.Write(line, 0, line.Length);



request.ContentLength = stream.Length;

Stream requestStream = request.GetRequestStream();

stream.Position = 0L;
stream.CopyTo(requestStream);
stream.Close();

requestStream.Close();

using (var response = request.GetResponse())
using (var responseStream = response.GetResponseStream())
using (var mstream = new MemoryStream())

responseStream.CopyTo(mstream);
return mstream.ToArray();



/// <summary>
/// 上传文件
/// </summary>
public class UploadFile

public UploadFile()

ContentType = "application/octet-stream";

public string Name get; set;
public string Filename get; set;
public string ContentType get; set;
public byte[] Data get; set;

参考技术C 你说的这个应该是标准的文件上传。
可以使用 System.Net.WebClient.UploadFile方法。追问

用这个方法提交还是不行,返回:远程服务器返回错误: (500) 内部服务器错误。
和我使用string提交是同一个返回错误,这表示发送过去的数据类型不匹配

追答

你先建一个普通的html文本,用form表单去提交,看能否成功。

追问

已经不需要了。对方的这个接口根本没开放走不通。

本回答被提问者和网友采纳

请教高手C#如何POST 一个XML文件到服务器

不熟悉C#,请教高手,我想用POST方法把一个放在D盘名为 "test.xml" 的文件发送到IP为192.168.X.XX的服务器上,请问应该如何写这段程序?谢谢!

参考技术A <from method="post" >
<input type="file" name="file" />这就是上传文件的控件啊
参考技术B 可以使用文件流的方式上传,然后接收到保存就可以了 参考技术C webservice的方法,上网上搜索下相关文档学习下 参考技术D 服务器接口是怎么写的?

以上是关于c#如何post文件流的主要内容,如果未能解决你的问题,请参考以下文章

在 C# 中使用 HTTP POST 发送文件 [关闭]

C# IO流如何清空本地txt文件

java http post 同时发送文件流与数据

django:如何将传入的 POST 数据作为类似文件的 obj 进行流处理

请教高手C#如何POST 一个XML文件到服务器

如何在 C# 中从内存流中播放 MP3?