赞
踩
using Microsoft.AspNetCore.Mvc; using System; using System.IO; using System.Threading.Tasks; namespace MyAPI.Controllers { [ApiController] [Route("[controller]")] public class OCRController : ControllerBase { [HttpPost("OCR")] public async Task<IActionResult> OCRTextAsync() { try { // 检查是否有文件被上传 if (Request.Form.Files.Count > 0) { // 获取上传的文件 var file = Request.Form.Files[0]; // 将文件转换为字节数组 using (var memoryStream = new MemoryStream()) { await file.CopyToAsync(memoryStream); byte[] imageData = memoryStream.ToArray(); return Ok("OCR result"); } } else { return BadRequest("No file uploaded"); } } catch (Exception ex) { return StatusCode(500, $"Internal server error: {ex}"); } } } }
调用示例代码:
private async void button1_Click(object sender, EventArgs e) { try { OpenFileDialog fileDialog = new OpenFileDialog(); fileDialog.Multiselect = true; fileDialog.Title = "请选择图片"; // fileDialog.Filter = "所有文件(*pdf*)|*.jpg*"; //设置要选择的文件的类型 if (fileDialog.ShowDialog() == DialogResult.OK) { string file = fileDialog.FileName;//返回文件的完整路径 // textBox1.Text = file; pictureBox1.Image = Image.FromFile(file); MemoryStream stream = new MemoryStream(); pictureBox1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] imagedata = stream.GetBuffer(); await TestApiAsync(imagedata); } } catch (Exception ex) { MessageBox.Show("请选择正确的图片"); } } private async Task TestApiAsync(byte[] imageData) { string url = "http://localhost:5000/api/OCR/OCR"; // 创建 HttpClient 实例 using (var httpClient = new HttpClient()) using (var formData = new MultipartFormDataContent()) { try { formData.Add(new ByteArrayContent(imageData), "file", "image.jpg"); // 发送 POST 请求到接口 HttpResponseMessage response = await httpClient.PostAsync(url, formData); // 检查响应是否成功 if (response.IsSuccessStatusCode) { // 读取响应内容 string result = await response.Content.ReadAsStringAsync(); Console.WriteLine("OCR 结果:" + result); } else { Console.WriteLine("请求失败,状态码:" + response.StatusCode); } } catch (Exception ex) { Console.WriteLine("发生异常:" + ex.Message); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。