调用ocr.space API时“没有上传文件或提供URL”

我试图从我的C#应用​​程序中调用此API: https : //ocr.space/OCRAPI

当我从curl调用它时,它运行正常:

curl -k --form "file=@filename.jpg" --form "apikey=helloworld" --form "language=eng" https://api.ocr.space/Parse/Image 

我这样实现了它:

  [TestMethod] public async Task Test_Curl_Call() { var client = new HttpClient(); String cur_dir = Directory.GetCurrentDirectory(); // Create the HttpContent for the form to be posted. var requestContent = new FormUrlEncodedContent(new[] { new KeyValuePair( "file", "@filename.jpg"), //I also tried "filename.jpg" new KeyValuePair( "apikey", "helloworld" ), new KeyValuePair( "language", "eng")}); // Get the response. HttpResponseMessage response = await client.PostAsync( "https://api.ocr.space/Parse/Image", requestContent); // Get the response content. HttpContent responseContent = response.Content; // Get the stream of the content. using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync())) { // Write the output. String result = await reader.ReadToEndAsync(); Console.WriteLine(result); } } 

我得到了这个答案:

 { "ParsedResults":null, "OCRExitCode":99, "IsErroredOnProcessing":true, "ErrorMessage":"No file uploaded or URL provided", "ErrorDetails":"", "ProcessingTimeInMilliseconds":"0" } 

任何线索?

"file=@filename.jpg"的@字符是什么?

我将我的filename.jpg文件放在项目测试项目bin / debug目录中,并在调试模式下运行我的测试项目。

所以我不认为错误指向文件不在预期的位置。 我宁愿怀疑我的代码中存在语法错误。

错误消息告诉您错误:

没有上传文件或提供url

您在代码中向服务发送了一个文件名,但这与给curl文件名不同。 curl足够聪明,可以读取文件并根据您的请求上传内容 ,但在您的C#代码中,您必须自己完成。 步骤将是:

  1. 从磁盘读取文件字节。
  2. 创建一个包含两部分的多部分请求:API密钥(“helloworld”)和文件字节。
  3. 将此请求发布到API。

幸运的是,这很容易。 此问题演示了设置多部分请求的语法。

这段代码对我有用:

 public async Task TestOcrAsync(string filePath) { // Read the file bytes var fileBytes = File.ReadAllBytes(filePath); var fileName = Path.GetFileName(filePath); // Set up the multipart request var requestContent = new MultipartFormDataContent(); // Add the demo API key ("helloworld") requestContent.Add(new StringContent("helloworld"), "apikey"); // Add the file content var imageContent = new ByteArrayContent(fileBytes); imageContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); requestContent.Add(imageContent, "file", fileName); // POST to the API var client = new HttpClient(); var response = await client.PostAsync("https://api.ocr.space/parse/image", requestContent); return await response.Content.ReadAsStringAsync(); }