c# 桌面开发上传文件不成功:代码如下
private string HttpPostData(string url, int timeOut, string fileKeyName,string filePath)
{
string responseContent;
var memStream = new MemoryStream();
var webRequest = (HttpWebRequest)WebRequest.Create(url);
// 边界符
var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
// 边界符
var beginBoundary = Encoding.UTF8.GetBytes("--" + boundary + "\r\n"); //用ASCII编码方式也不成功
var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
// 最后的结束符
var endBoundary = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n"); //用ASCII编码方式也不成功
// 设置属性
webRequest.Method = "POST";
webRequest.Timeout = timeOut;
webRequest.ContentType = " multipart/form-data; boundary=" + boundary;
// 写入文件
string filePartHeader = boundary + "\r\n" +
"Content-Disposition:form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
"Content-Type:application/octet-stream\r\n\r\n";
var header = string.Format(filePartHeader, fileKeyName, filePath);
var headerbytes = Encoding.UTF8.GetBytes(header); //用ASCII编码方式也不成功
memStream.Write(headerbytes, 0, headerbytes.Length);
var buffer = new byte[1024];
int bytesRead; // =0
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
memStream.Write(buffer, 0, bytesRead);
}
// 写入结束边界符
memStream.Write(endBoundary, 0, endBoundary.Length);
webRequest.ContentLength = memStream.Length;
var requestStream = webRequest.GetRequestStream();
memStream.Position = 0;
var tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close();
var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(),Encoding.GetEncoding("utf-8")))
{
responseContent = httpStreamReader.ReadToEnd();
}
fileStream.Close();
httpWebResponse.Close();
webRequest.Abort();
return responseContent; //返回的结果:{"errcode":-1,"errmsg":"系统繁忙"}
}
有C#上传文件的例子吗?谢谢了
-------------------------
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。