1 回答
TA贡献1784条经验 获得超2个赞
尝试这个:
var formData = new FormData();
formData.append("image", fileInputElement.files[0]);
var request = new XMLHttpRequest();
request.open("POST", "http://example.com/submitform.php");
request.send(formData);
并在服务器上将其上传到另一台服务器:
string responseString;
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
var formData = new MultipartFormDataContent {
{ new StreamContent(fileStream), @"image", Path.GetFileName(filePath) }
};
var request = (HttpWebRequest)WebRequest.Create("URL");
request.Method = WebRequestMethods.Http.Post;
request.AllowWriteStreamBuffering = false;
request.SendChunked = true; // set to true to avoid exception when AllowWriteStreamBuffering = false and ContentLength is not set
request.Headers.Add("abc", "def");
request.ContentType = formData.Headers.ContentType.ToString();
try
{
// Get the request stream with the default timeout
using (Stream requestStream = await request.GetRequestStreamAsyncWithTimeout())
{
// Upload the file with no timeout
await formData.CopyToAsync(requestStream);
}
// Get response with the default timeout, and parse the response body
using (WebResponse response = await request.GetResponseAsyncWithTimeout())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
{
responseString = reader.ReadToEnd();
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.Timeout)
{
throw new TimeoutException("Timeout while uploading file.", ex);
}
throw;
}
}
ResultModel result = JsonConvert.DeserializeObject<ResultModel>(responseString);
这些扩展可以让您的上传请求在文件较大或连接速度较慢时不会超时:
public static class WebRequestExtensions
{
public static async Task<Stream> GetRequestStreamAsyncWithTimeout(this WebRequest request, int? millisecondsTimeout = null)
{
Task<Stream> getTask = request.GetRequestStreamAsync();
if (await Task.WhenAny(getTask, Task.Delay(request.Timeout)) == getTask)
{
// task completed without timeout
return getTask.Result;
}
else
{
// timeout
var ex = new TimeoutException();
throw new WebException(ex.Message, ex, WebExceptionStatus.Timeout, null);
}
}
public static async Task<WebResponse> GetResponseAsyncWithTimeout(this WebRequest request, int? millisecondsTimeout = null)
{
Task<WebResponse> getTask = request.GetResponseAsync();
if (await Task.WhenAny(getTask, Task.Delay(request.Timeout)) == getTask)
{
// task completed without timeout
return getTask.Result;
}
else
{
// timeout
var ex = new TimeoutException();
throw new WebException(ex.Message, ex, WebExceptionStatus.Timeout, null);
}
}
private static T AsyncToSyncWithTimeout<T>(
Func<AsyncCallback, object, IAsyncResult> begin,
Func<IAsyncResult, T> end,
int millisecondsTimeout)
{
var iar = begin(null, null);
if (!iar.AsyncWaitHandle.WaitOne(millisecondsTimeout))
{
var ex = new TimeoutException();
throw new WebException(ex.Message, ex, WebExceptionStatus.Timeout, null);
}
return end(iar);
}
}
添加回答
举报