程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

The backend Django of vue2 uploading pictures related to static resources realizes file operation

編輯:Python

List of articles

  • One 、 Static resource allocation
    • 1 settings To configure Splicing path
    • 2 Create under the folder with the same name of the project static Folders and subfolders
  • Two 、 Back end code To upload pictures
    • 1. View
    • 2. route
  • 3、 ... and 、 Knowledge review File operations


One 、 Static resource allocation

1 settings To configure Splicing path

STATICFILES_DIRS = (os.path.join(BASE_DIR, ‘static’),)
STATICFILES_DIRS =(os.path.join(BASE_DIR, ‘static’),)

2 Create under the folder with the same name of the project static Folders and subfolders

Can be created according to the address of the static resource You can also create your own Match addresses one by one
for example : /static/images/logos/ lenovo .png

Two 、 Back end code To upload pictures

1. View

with open(file_name, ‘wb’) as f:
'wb' w write in b Binary form wb Write... In binary format

# Upload brand logo
class UploadBrandLogo(APIView):
def post(self, request):
print(' Uploaded image data :', request.data, type(request.data))
# Get file object
file = request.data.get('file')
# file.file Uploaded file byte stream object 
# file.name File name 
# file_path File path 
# Splicing path
static_path = 'static/images/logos'
file_path = os.path.join(settings.BASE_DIR, static_path)
file_name = os.path.join(file_path, file.name)
# Save the picture
with open(file_name, 'wb') as f:
f.write(file.file.read())
data = {

'static_path': static_path,
'code': 200, 'msg': ' Upload the picture successfully '
}
return Response(data)

2. route

Be careful : When brand routing uses view sets The route of brand image uploading can be written into the main route to avoid repetition

urlpatterns = [
path('brands/logos/', UploadBrandLogo.as_view()),
]

3、 ... and 、 Knowledge review File operations




  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved