1、index.html
<script src="js/jquery-1.12.4.min.js"></script> <script> function fucTest() { let form_data = new FormData(); let file_info = $("#img")[0].files[0]; form_data.append('img', file_info); $.ajax({ url: "http://127.0.0.1:8000/test/", // ocr服务url type: 'POST', data: form_data, processData: false, contentType: false, beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}") }, success: function (ret) { $("#result").text(ret) } }) } </script> ...... <input type="file" name="img" id="img"> <button onclick="fucTest()">ocr test</button> <p id="result"></p>
2、views.py
class Index(View): def get(self, request): return render(request, 'index.html') class OCRView(View): def post(self, request): img = request.FILES.get('img') parser = ImageFile.Parser() for chunk in img.chunks(): parser.feed(chunk) img = parser.close() img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR) result = "图像的尺寸:" + img.shape[1] + "_" + img.shape[0] return HttpResponse(result)
3、 urls.py
urlpatterns = [ path('', Index.as_view(), name='index'), path('test/', OCRView.as_view(), name='test'), ]