Вот мой код:
Код: Выделить всё
public async Task UploadFileAsync(string filePath, string purposeTo = "ocr")
{
// 2 lines below are done in the constructor
//_httpClient = new HttpClient();
//_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", myApiKeyMistral);
if (!File.Exists(filePath)) return ($"Erreur, fichier non trouvé: {filePath}");
FileInfo fileInfo = new FileInfo(filePath);
if (fileInfo.Length == 0) return ($"Erreur, fichier vide : {filePath}");
string BaseUrlUpload = _baseUrlMistral + "files"; // in general "https://api.mistral.ai/v1/files"
using var fileStream = File.OpenRead(filePath);
using var fileContent = new StreamContent(fileStream);
string mimeType = GetMimeType(filePath); // "application/pdf" if file is .PDF, text/plain if .txt, etc.
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(mimeType);
using (var form = new MultipartFormDataContent())
{
form.Add(fileContent, "file", System.IO.Path.GetFileName(filePath)); // "file" NOT "file_name"
form.Add(new StringContent(purposeTo), "purpose");
try
{
var resp = await _httpClient.PostAsync(BaseUrlUpload, form);
if (!resp.IsSuccessStatusCode)
{
// Gérez les erreurs ici
string erreur = await resp.Content.ReadAsStringAsync();
return $"Erreur HTTP : {resp.StatusCode} - {resp.ReasonPhrase} - {erreur}";
}
var json = await resp.Content.ReadAsStringAsync();
using var doc = JsonDocument.Parse(json);
return doc.RootElement.GetProperty("id").GetString();
}
catch (Exception ex)
{
return $"Erreur lors de l'upload du fichier : {ex.Message}";
}
}
}
Код: Выделить всё
Unprocessable Entity - {"detail": "Invalid file format.", "message": "Received file with mimetype text/plain, only application/pdf, image/.*, application/vnd.openxmlformats-officedocument.wordprocessingml.document, ... text/troff, text/x-dokuwiki are currently supported"}
Подробнее здесь: https://stackoverflow.com/questions/798 ... api-upload
Мобильная версия