【问题标题】:How to display image in django using HttpResponse如何使用 HttpResponse 在 django 中显示图像
【发布时间】:2023-12-14 03:31:01
【问题描述】:

我正在尝试使用以下行显示 python 脚本输出的图像,但不是在浏览器中显示,而是下载文件而不是显示的代码

这是我在views.py中创建的函数:

def adc(请求): 文件 = "C:\Users\TheBoss\Downloads\New_test.xlsx" df = pd.read_excel(file, sheet_name='Graph')

plt.plot(df['Date'], df['Video Device - Not Responding'], label = 'Video Device - Not Responding')
#plt.plot(df['Date'], df['30th Apr'], 'b', label = '30-Apr')
plt.xticks(rotation=45)

plt.tick_params(axis='x', which='major', labelsize=6)
# naming the y axis
plt.ylabel('Condition Count')

# giving a title to my graph
plt.title('Condition')

# function to show the plot
plt.legend()
#plt.show()
plt.savefig('C:\\Users\\TheBoss\\Downloads\\test.png')


image_data = open("C:\\Users\\TheBoss\\Downloads\\test.png", "rb").read()
return HttpResponse(image_data, content_type="test/png")

【问题讨论】:

  • 尝试将Content-Disposition 标头设置为inlineHere 是一个如何做到这一点的例子。我认为 Django 会自动将此设置为 attachment 以进行文件响应。关于Content-Disposition 的附加信息是here
  • 感谢您的回复.....我试过但仍然下载而不是显示......

标签: python django httpresponse


【解决方案1】:

通常,这应该足以内联显示图像。

def adc(request): 
    file = "C:\Users\TheBoss\Downloads\New_test.xlsx"
    df = pd.read_excel(file, sheet_name='Graph')

    plt.plot(df['Date'], df['Video Device - Not Responding'], label = 'Video Device - Not Responding')
    plt.xticks(rotation=45)
    plt.tick_params(axis='x', which='major', labelsize=6)
    plt.ylabel('Condition Count')
    plt.title('Condition')
    plt.legend()
    
    buffer = io.BytesIO()
    plt.savefig(buffer, format='png')
    return HttpResponse(buffer.getvalue(), content_type="test/png")

它应该在大多数浏览器中显示为图像,如果你想在 HTML 中插入图像,你会使用一个简单的

<img src="{% url 'my_image' %}">

根据经验,我知道这适用于 Edge、Firefox 和 Opera。有时浏览器需要额外的说服力来显示内联图像,在这种情况下,将标头 Content-Disposition 设置为 inline 通常有效。

【讨论】:

  • 谢谢我试过了,但它也下载文件不显示