Привет! У меня есть требование загрузить zip-файл на сервер с помощью multipartformload httpwebrequest. Я попробовал известный пример multipartformload, но не повезло. Может кто-нибудь, пожалуйста, помогите мне в этом. Вот мой полный код. Он всегда зависает при выполнении веб-запроса в течение длительного времени и, наконец, выдает ошибку тайм-аута. Может кто-нибудь, пожалуйста, помогите мне в этом. Вот мой код,
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Net.Cache;
using RestSharp;
using System.Net.Http;
namespace FileUploadTool
{
public static class Method1
{
private static readonly Encoding encoding = Encoding.UTF8;
public static HttpWebResponse MultipartFormPost(string postUrl, string userAgent, Dictionary<string, object> postParameters)
{
string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
string contentType = "multipart/form-data; boundary=" + formDataBoundary;
byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);
return PostForm(postUrl, userAgent, contentType, formData);
}
private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData)
{
HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
if (request == null)
{
throw new NullReferenceException("request is not a http request");
}
// Set up the request properties.
request.Method = "POST";
request.ContentType = contentType;
// request.UserAgent = userAgent;
request.CookieContainer = new CookieContainer();
request.ContentLength = formData.Length;
request.KeepAlive = true;
// request.ContentType = "multipart/form-data";
request.Accept = "application/json";
request.Expect = "";
request.SendChunked = true;
// You could add authentication here as well if needed:
// request.PreAuthenticate = true;
// request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
//Add header if needed
// request.Headers.Add(headerkey, headervalue);
// Send the form data to the request.
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(formData, 0, formData.Length);
requestStream.Close();
}
int i = request.Timeout;
request.Timeout = 100000000;
return request.GetResponse() as HttpWebResponse;
}
private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
{
Stream formDataStream = new System.IO.MemoryStream();
bool needsCLRF = false;
foreach (var param in postParameters)
{
if (needsCLRF)
formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));
needsCLRF = true;
if (param.Value is FileParameter) // to check if parameter if of file type
{
FileParameter fileToUpload = (FileParameter)param.Value;
// Add just the first part of this param, since we will write the file data directly to the Stream
string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
boundary,
param.Key,
fileToUpload.FileName ?? param.Key,
fileToUpload.ContentType ?? "application/octet-stream");
formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));
// Write the file data directly to the Stream, rather than serializing it to a string.
formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);
}
else
{
string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
boundary,
param.Key,
param.Value);
formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
}
}
// Add the end of the request. Start with a newline
string footer = "\r\n--" + boundary + "--\r\n";
formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));
// Dump the Stream into a byte[]
formDataStream.Position = 0;
byte[] formData = new byte[formDataStream.Length];
formDataStream.Read(formData, 0, formData.Length);
formDataStream.Close();
return formData;
}
public class FileParameter
{
public byte[] File { get; set; }
public string FileName { get; set; }
public string ContentType { get; set; }
public FileParameter(byte[] file) : this(file, null) { }
public FileParameter(byte[] file, string filename) : this(file, filename, null) { }
public FileParameter(byte[] file, string filename, string contenttype)
{
File = file;
FileName = filename;
ContentType = contenttype;
}
}
}
}
И вот как я называю этот код,
public string CallFileUploadCode()
{
byte[] data;
string strResponse = string.Empty;
try
{
using (FileStream fs = File.Open(FileUploadProperties.CompleteFileName, FileMode.OpenOrCreate, FileAccess.Read))
{
data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
}
Dictionary<string, object> postParameters = new Dictionary<string, object>();
postParameters.Add("sourceKey", FileUploadProperties.FileName);
postParameters.Add("revisionNumber", FileUploadProperties.RevisionVersion);
postParameters.Add("revisionText", FileUploadProperties.RevisionText);
postParameters.Add("contentSize", FileUploadProperties.ContentSize);
postParameters.Add("contentType", FileUploadProperties.ContentType);
postParameters.Add("contentFilename", FileUploadProperties.FileName);
postParameters.Add("contentTimestamp", FileUploadProperties.ContentTimestamp);
postParameters.Add("dataSource", FileUploadProperties.DataSource);
postParameters.Add("dataNamespace", FileUploadProperties.DataNameSpace);
postParameters.Add("dataRecordType", FileUploadProperties.DataRecordType);
postParameters.Add("dataRecordVersion", FileUploadProperties.RevisionVersion);
postParameters.Add("dataRecordMeta", FileUploadProperties.DataRecordMeta);
postParameters.Add("dataGroup", FileUploadProperties.DataGroup);
postParameters.Add("dataTitle", FileUploadProperties.FileName);
postParameters.Add("dataDescription", FileUploadProperties.FileName);
postParameters.Add("dataOwner", FileUploadProperties.DataOwner);
postParameters.Add("dataEffectiveDate", FileUploadProperties.DataEffectiveDate);
postParameters.Add("dataExpirationDate", FileUploadProperties.DataExpirationDate);
postParameters.Add("dataTags", FileUploadProperties.DataTags);
string strPostMetaData = JsonConvert.SerializeObject(postParameters);
Dictionary<string, object> postParameters1 = new Dictionary<string, object>();
postParameters1.Add("metaData", strPostMetaData);
postParameters1.Add("fileData", new Method1.FileParameter(data, Path.GetFileName(FileUploadProperties.CompleteFileName), FileUploadProperties.ContentType));
string strPostData = JsonConvert.SerializeObject(postParameters1);
//postParameters.Add("fileData", new Method1.FileParameter(data, FileUploadProperties.CompleteFileName, FileUploadProperties.ContentType));
// postParameters.Add("fileData", new Method1.FileParameter(data, FileUploadProperties.CompleteFileName, FileUploadProperties.ContentType));
HttpWebResponse webResponse = Method1.MultipartFormPost(FileUploadProperties.UploadService,"someone", postParameters1);
// Process response
StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
string fullResponse = responseReader.ReadToEnd();
strResponse = fullResponse;
webResponse.Close();
}
catch (Exception ex)
{
throw ex;
}
return strResponse;
}