1、在url.py文件中的配置
導入相關的庫,在Python2.0后,要用re_path
from django.urls import path,re_path from django.views.static import serve urlpatterns = [ path(r'similar_img/',app06_views.file_receiving), re_path(r'^static/(?P<path>.*)$', serve, {'document_root': 'C:/Users/Administrator/Desktop/Django_ALL2/project_all/static'}), ]
static文件夾是放圖片等文件的,serve是導入的庫,document_root后面的路徑是存放圖片文件的文件夾路徑
static文件夾內部可以建立文件夾,如圖片庫文件夾(database)、上傳的圖片存放文件夾(image)
2、在view.py文件中的配置
1 def file_receiving(request): 2 if request.method == 'GET': 3 return render(request,'similar_img.html') 4 elif request.method == 'POST': 5 file1 = request.FILES.get('upfile') 6 print(file1.name) 7 file1_path = './static/image/'+file1.name 8 # file1_path = os.path.join(r'./app06_similar_img/receive_img',file1.name) 9 f = open(file1_path,mode='wb') 10 for data in file1.chunks(): 11 f.write(data) 12 f.close() 13 #調用搜索相似產品圖片函數,並呈現頁面 14 sim_img_datas = search_img(os.getcwd()+'\\static\\image\\'+file1.name) 15 print(type(sim_img_datas),sim_img_datas) 16 # sim_img_datas['result'] = [] 17 18 if sim_img_datas['result']: 19 sim_img_data = [] 20 for item in sim_img_datas['result']: 21 sim_img_data1 = [] 22 sim_img_data1.append(item['score'])#相似度得分 23 img_name = json.loads(item['brief']) 24 sim_img_data1.append(img_name['name'])#相似圖片名稱 25 26 sim_img_data.append(sim_img_data1) 27 else: 28 sim_img_data = [['0','沒有查找到相似圖片']] 29 30 print(sim_img_data) 31 success = ['上傳成功!'] 32 # os.remove(file1_path) 33 database_path = '/static/database/'+file1.name#去掉那個點,才能顯示圖片 34 return render(request, 'similar_img.html',{'success': success[0],'file1_path':database_path,'sim_img_datas':sim_img_data}) 35 else: 36 return redirect('/similar_img/')
注意:返回給前端頁面的本地文件路徑是個相對路徑,並且沒有點
3、前端頁面的配置
相對路徑放在img標簽的src屬性中
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <h1>Cichic相似圖片搜索</h1> 9 <hr><br> 10 <div style="width: 500px"> 11 <span style="text-align: center"> 12 <form action="/similar_img/" method="POST" enctype="multipart/form-data"> 13 <input type="file" name="upfile"/> 14 <input type="submit" value="搜索Cichic相似圖片"/> 15 </form> 16 <div style="color:#FF0000;">{{ success }}</div> 17 </span> 18 <span> 19 <h3>上傳文件的圖片</h3> 20 <a href="{{ file1_path }}" target="_blank" > 21 <img width="60px" height="80px" class="lazyload" alt="展示需要搜索的相似圖片" src={{ file1_path }}> 22 </a> 23 </span> 24 </div> 25 <hr><br> 26 <h3>相似圖片展示</h3> 27 <div> 28 <table border="1" rules="all" style=" text-align:left"> 29 {% for sim_img_data1 in sim_img_datas %} 30 <tr> 31 <td>相似度:{{ sim_img_data1.0 }}</td> 32 <td>圖片名稱:{{ sim_img_data1.1 }}</td> 33 <td> 34 <a href="/static/database/{{ sim_img_data1.1 }}" target="_blank" > 35 <img width="60px" height="80px" class="lazyload" src="/static/database/{{ sim_img_data1.1 }}"> 36 </a> 37 </td> 38 </tr> 39 {% endfor %} 40 </table> 41 </div> 42 43 </body> 44 </html>