请帮助显示此图片。我正在尝试将python脚本转换为webservice。
模板index.html
<body>
{% block pagecontent %}
{{ form }}
<form action="select.html" id="file-upload-form" class="modal-content animate" enctype="multipart/form-data" method="post" id="uploadForm">
Select Files: <input type="file" name="myfile" required ></br> <span id=disp> </span> <!-- <a href="/about/">Button</a> -->
<button type="submit" class="btn btn-primary" id='upload-btn'> Upload File </button>
</form>
{% endblock %}
</body>
模板select.html
<div>
{{context}}
<img src="{{context}}" width="200" height="200">
</div>
应用urls.py
urlpatterns = [
url(r'^$', index),
url(r'^index', index),
url(r'^select', select),
]
Apps views.py
def index(request):
return render_to_response("index.html")
def select(request):
global response
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
img = pdf2image.convert_from_path(filename)
response = HttpResponse(content_type="image/png")
for i,image in enumerate(img):
image.save(response, "png")
context = {'img':response}
return render_to_response('select.html', context)
终端API响应。
System check identified no issues (0 silenced).
March 18, 2018 - 13:58:31
Django version 2.0.3, using settings 'myproject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[18/Mar/2018 13:58:36] "GET / HTTP/1.1" 200 796
[18/Mar/2018 13:59:25] "POST /select.html HTTP/1.1" 200 538
提前致谢。
答案 0 :(得分:0)
您需要编写一个仅返回图像的单独视图:
from PIL import Image
def send_image(request):
filename = requests.GET.get('file')
fs = FileSystemStorage()
if fs.exists(filename):
try:
image = pdf2image.convert_from_path(fs.path(filename))
response = HttpResponse(content_type="image/png")
image.save(response, "png")
return response
except:
error_image = Image.new('RGBA', (1, 1), (255,0,0,0))
response = HttpResponse(content_type="image/jpeg")
error_image.save(response, "JPEG")
return response
else:
error_image = Image.new('RGBA', (1, 1), (255,0,0,0))
response = HttpResponse(content_type="image/jpeg")
error_image.save(response, "JPEG")
return response
然后使用PDF文件的名称这样调用它。
<img src="/send_image?file=name_of_file.pdf" />
在您的代码中,修改您的select
方法:
def select(request):
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
context = {'img':filename}
return render_to_response('select.html', context)
然后是你的模板:
<div>
<img src="/send_image?file={{img}}" width="200" height="200">
</div>