我正在使用 HttpClient 将二进制文件发布到 Azure 托管的服务器。对于大小不太大的文件,该请求需要很长时间才能传递。有时,当客户端因超时而取消任务时,服务器会收到请求。我使用以下代码异步上传数据:
public async Task<HttpResponseMessage> UploadFile(byte[] file)
{
videoThumbName = Guid.NewGuid().ToString();
var progress = new System.Net.Http.Handlers.ProgressMessageHandler();
progress.HttpSendProgress += progress_HttpSendProgress;
using (var client = HttpClientFactory.Create(progress))
{
client.BaseAddress = new Uri(GlobalVariables.host);
// Set the Accept header for BSON.
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/bson"));
var request = new uploadFileModel { data = file, dateCreated = DateTime.Now, fileName = fileName, username = loggedUser, VideoThumbName = videoThumbName};
// POST using the BSON formatter.
MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
var m = client.MaxResponseContentBufferSize;
var result = await client.PostAsync("api/media/upload", request, bsonFormatter);
return result.EnsureSuccessStatusCode();
}
}
服务器端代码如下所示(为了简洁起见,我留下了一些代码):
[HttpPost]
[Route("upload")]
public async Task<HttpResponseMessage> Upload(uploadFileModel model)
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
if (ModelState.IsValid)
{
string thumbname = model.VideoThumbName;
string tempPath = HttpContext.Current.Server.MapPath("~/video");
string sourceFilePath = Path.Combine(HttpContext.Current.Server.MapPath("~/video"), model.fileName);
string pathToThumbs = Path.Combine(HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/thumbs"), thumbname + ".jpg");
string finalPath = Path.Combine(HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/flv"), model.fileName);
string thumbPath = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/thumbs");
string vidDuration = "";
string videoDurationSec = "";
int maxWidth = 380;
int maxHeight = 360;
try
{
File.WriteAllBytes(sourceFilePath, model.data);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
var ffMpegThumb = new NReco.VideoConverter.FFMpegConverter();
ffMpegThumb.GetVideoThumbnail(sourceFilePath, pathToThumbs);
var ffmpegVid = new NReco.VideoConverter.FFMpegConverter();
ffmpegVid.ConvertMedia(sourceFilePath, Format.mp4, finalPath, Format.mp4, new ConvertSettings() { VideoCodec = "h264" });
return result;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}
是否有可能是因为我的互联网连接请求延迟了?我发送的文件大小甚至没有那么大,它们的大小约为 1-2 mbs。我想知道更大的文件需要多长时间。
我可以改进这个过程吗?