I have a pretty crazy problem and I hope someone can give me some advice on how to fix it.
On the client side, I upload a multipart form to a server using C #. In the form there is a field for an MD5 hash and a field for an audio file.
The problem is that it sometimes happens that an uploaded audio file has a line break at the end of the file that is not present in the original file on the client side. And this of course causes the MD5 hash check to fail.
I am amazed that this only happens sometimes. From 200 requests there is one with the problem described.
Here is the code from my HttpMultipartFormSender class:
public class HttpMultipartFormSender
{
private HttpRequestMessage _requestMessage;
public HttpMultipartFormSender(string requestUri)
{
UploadProgressHandler = new ProgressMessageHandler();
var boundary = "----------" + DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture);
Content = new MultipartFormDataContent(boundary);
_requestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri);
}
public MultipartFormDataContent Content { get; set; }
public ProgressMessageHandler UploadProgressHandler { get; }
public async Task<bool> SendFormAsync()
{
_requestMessage.Content = Content;
var client = HttpClientFactory.Create(UploadProgressHandler);
client.Timeout = TimeSpan.FromMinutes(30);
var httpResponse = await client.SendAsync(_requestMessage);
if (!httpResponse.IsSuccessStatusCode)
{
throw new InvalidOperationException("Exception thrown while file upload");
}
return true;
}
#endregion
}
And the usage looks like:
VmPropUserMessage = $"File: {Path.GetFileName(filePath)} is uploading...";
await using var fileStream =
new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
var md5StringContent = new StringContent(GetFileMd5(filePath));
var fileStreamContent = new StreamContent(fileStream);
fileStreamContent.Headers.Add("Content-Type", "application/octet-stream");
var formSender = new HttpMultipartFormSender($"{VmPropSelectedTranscoder.Url}/upload");
formSender.UploadProgressHandler.HttpSendProgress += FileUploadProgressChanged;
formSender.Content.Add(md5StringContent, "file_hash");
formSender.Content.Add(fileStreamContent, "file", filePath);
await formSender.SendFormAsync();
On the Server side i use this code sniped to store the stream from the request:
private static void SaveFile(TranscodingJobModel transcodingJob, Stream requestFileContent)
{
var uploadedFilePath = $"{AppConfig.AudioUploadDir}\\{transcodingJob.GetTranscodingJobTmpFileName}";
using (var fileSaveStream = File.Create(uploadedFilePath))
{
requestFileContent.CopyTo(fileSaveStream);
fileSaveStream.Flush(true);
fileSaveStream.Close();
requestFileContent.Close();
}
}
Sometimes i have this result:
On client side file ends with only one new line:
On server side file ends with two new lines:
Have somebody an idea why this occurs?
Thanks in advance

