POST接口上传文件1M以下没问题超过1M提示500错误
POST接口上传文件1M以下没问题超过1M提示500错误
public static string webPost(string apiurl, string fpath, string type, string access_token, AttachmentInfo atts)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
ServicePointManager.CheckCertificateRevocationList = true;
ServicePointManager.DefaultConnectionLimit = 512;
ServicePointManager.Expect100Continue = true;
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
//1.HttpWebRequest
System.GC.Collect();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiurl);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = type;
request.KeepAlive = false;
//request.Credentials = CredentialCache.DefaultCredentials;
string head = "Bearer " + access_token;
request.Headers.Add("Authorization", head);
request.Timeout = 1000 * 3600;
request.ReadWriteTimeout = 1000 * 3600;
using (Stream stream = request.GetRequestStream())
{
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
byte[] buffer = new byte[4096];
int bytesRead = 0;
string header = string.Format(headerTemplate, "file", atts.Name);
byte[] headerbytes = Encoding.GetEncoding("UTF-8").GetBytes(header);
//1.2 file
stream.Write(boundarybytes, 0, boundarybytes.Length);
stream.Write(headerbytes, 0, headerbytes.Length);
using (FileStream fileStreamss = new FileStream(fpath, FileMode.Open, FileAccess.Read))
{
while ((bytesRead = fileStreamss.Read(buffer, 0, buffer.Length)) != 0)
{
stream.Write(buffer, 0, bytesRead);
}
}
//1.3 form end
stream.Write(endbytes, 0, endbytes.Length);
}
//2.WebResponse
string result;
try
{
request.ProtocolVersion = HttpVersion.Version10;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string text = streamReader.ReadToEnd();
result = text;
response.Close();
}
catch (Exception ex)
{
result = ex.Message;
}
finally
{
request.Abort();
System.GC.Collect();
}
return result;
}