我有一种方法可以将文件上传到我们的服务器。我在尝试上传大文件时看到标题中的错误。我尝试在 web.config 中将 maxRequestLength 从 35480 KB 增加,但我仍然看到错误。
<httpRuntime maxRequestLength="3548000" executionTimeout="1000" targetFramework="4.6.1"/>
我还尝试在这篇文章System.Net.ProtocolViolationException: You must write ContentLength bytes to the request stream 中提到的 using 语句中发出请求,然后再调用 [Begin]GetResponse无济于事。任何意见,将不胜感激。
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
webrequest.CookieContainer = cookies;
webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
webrequest.Method = "POST";
// Build up the post message header
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("--"); sb.Append(boundary); sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\""); sb.Append(fileFormName);
sb.Append("\"; filename=\""); sb.Append(Path.GetFileName(uploadfile)); sb.Append("\""); sb.Append("\r\n");
sb.Append("Content-Type: "); sb.Append("application/octet-stream"); sb.Append("\r\n");
sb.Append("\r\n");
string postHeader = sb.ToString();
byte[] postHeaderBytes = System.Text.Encoding.UTF8.GetBytes(postHeader);
// Build the trailing boundary string as a byte array. ensuring the boundary appears on a line by itself
byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
string strRead = "";
FileStream fileStream = null;
Stream requestStream = null;
WebResponse responce = null;
StreamReader responseStream = null;
try
{
fileStream = new FileStream(uploadfile, FileMode.Open, FileAccess.Read);
long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
webrequest.ContentLength = length;
using (requestStream = webrequest.GetRequestStream())
{
//requestStream = webrequest.GetRequestStream();
// Write out our post header
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
// Write out the file contents
byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { requestStream.Write(buffer, 0, bytesRead); }
// Write out the trailing boundary
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
responce = webrequest.GetResponse();
}
responseStream = new StreamReader(responce.GetResponseStream());
strRead = responseStream.ReadToEnd();
}
catch (Exception ex)
{
// handle error
}
finally
{
if( fileStream != null ) fileStream.Close();
if( requestStream != null ) requestStream.Close();
if( responseStream != null ) responseStream.Close();
if( responce != null ) responce.Close();
}
return strRead;