我有一个将文件上传到我们的服务器的方法。我在尝试上传大文件时看到标题中的错误。我尝试在 web.config 中从 35480 KB 增加 maxRequestLength,但我仍然看到错误。
<httpRuntime maxRequestLength="3548000" executionTimeout="1000" targetFramework="4.6.1"/>
我也尝试在 using 语句中发出请求,如这篇文章中所述 System.Net.ProtocolViolationException:在调用 [Begin]GetResponse 之前,您必须将 ContentLength 字节写入请求流,但无济于事。任何建议将不胜感激。
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("rn");
sb.Append("Content-Disposition: form-data; name=""); sb.Append(fileFormName);
sb.Append(""; filename=""); sb.Append(Path.GetFileName(uploadfile)); sb.Append("""); sb.Append("rn");
sb.Append("Content-Type: "); sb.Append("application/octet-stream"); sb.Append("rn");
sb.Append("rn");
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("rn--" + boundary + "rn");
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;
这是通过在system.webServer中设置maxAllowedContentLength来解决的。超出最大请求长度。