Пользователь выбирает файлы с помощью OpenFileDialog, эти файлы необходимо отправить в api, который хранит их в хранилище BLOB-объектов.
Я преобразовал эти файлы в поток и использовал его для отправки их в api, но файлы в хранилище кажутся поврежденными или нечитаемыми. В API нет ничего плохого, потому что его тестирование с помощью почтальона всегда успешно.
Вот код в проекте wpf
Модель
public class AttachmentModel
{
public Guid Id { get; set; }
public Stream FileStream { get; set; }
public string FileName { get; set; }
public string StorageFileName { get; set; }
public string Suffix { get; set; } = "";
public string GetMimeType()
{
switch (FileName.Split('.').LastOrDefault())
{
case "png":
return "image/png";
case "jpg":
return "image/jpeg";
case "svg":
return "image/svg+xml";
case "pdf":
return "application/pdf";
case "doc":
return "application/msword";
case "docx":
return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
case "xls":
return "application/vnd.ms-excel";
case "xlsx":
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
case "csv":
return "text/csv";
case "txt":
return "text/plain";
default:
return "";
}
}
}
Добавить вложение к списку вложений
Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
openFileDialog.Filter = "All Files(*.pdf;*.doc;*.docx;*.xls;*.xlsx;*.csv;*.png;*.jpg;*.svg;*.txt)|*.pdf;*.doc;*.docx;*.xls;*.xlsx;*.csv;*.png;*.jpg;*.svg;*.txt|" +
"PDF Files(*.pdf)|*.pdf|" +
"Document Files(*.doc;*.docx;*.xls;*.xlsx;*.csv)|*.doc;*.docx;*.xls;*.xlsx;*.csv|" +
"Image Files(*.png;*.jpg;*.svg)|*.png;*.jpg;*.svg|" +
"Text Files(*.txt)|*.txt";
openFileDialog.Multiselect = false;
Nullable<bool> result = openFileDialog.ShowDialog();
if (result == true)
{
Stream stream = openFileDialog.OpenFile();
AttachmentModel attachment = new AttachmentModel
{
Id = Guid.NewGuid(),
FileStream = stream,
FileName = openFileDialog.FileName.Split('\\').Last()
};
AttachmentThumbnails.Add(attachment);
}
Преобразовать поток в ByteArray
MultipartFormDataContent formData = new MultipartFormDataContent();
foreach (AttachmentModel attachment in AttachmentThumbnails)
{
attachment.StorageFileName = Guid.NewGuid().ToString();
var Bytes = ConvertToByteArray(attachment.FileStream);
var byteArrayContent = new ByteArrayContent(Bytes);
byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse(attachment.GetMimeType());
formData.Add(byteArrayContent, $"\"{attachment.StorageFileName}\"", $"\"{attachment.FileName}\"");
}
var response = await DataService.Instance.UploadAttachments(formData);
Загрузить данные формы в api
public async Task<(bool, object)> UploadAttachments(MultipartFormDataContent dataContent)
{
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsync($"https://localhost:6001/Document", dataContent);
if (response.IsSuccessStatusCode)
{
string cont = await response.Content.ReadAsStringAsync();
return (true, null);
}
else
return (false, response.ReasonPhrase);
}
}
catch (Exception e)
{
return (false, e.InnerException != null ? e.InnerException.Message : e.Message);
}
}