【Python】+Django+Vue+Element UI 實現圖片上傳功能


 

一、效果

 

 

二、前端代碼

僅修改action即可(這是后端上傳接口)

<el-upload class="upload-demo" action="http://127.0.0.1:8549/file/upload/" :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" multiple :limit="3" :on-exceed="handleExceed" :file-list="fileList">
  <el-button size="small" type="primary">點擊上傳</el-button>
  <div slot="tip" class="el-upload__tip">只能上傳jpg/png文件,且不超過500kb</div>
</el-upload>

三、后端代碼

3.1、urls.py文件

urlpatterns = [
    path('file/upload/', views.upload), # 上傳接口
]

3.2、新增views.upload代碼(直接復制即可)FileOperation.handle_upload_file寫自己對應的

@csrf_exempt  # 沒加這個會報錯Forbidden (CSRF cookie not set.)
def upload(request):
    if request.method == "POST":
        FileOperation.handle_upload_file(request.FILES.get('file'), str(request.FILES['file']))
        msg = {}
        msg['msg'] = '上傳成功'
        msg['success'] = True
    return HttpResponse(json.dumps(msg))

3.3、FileOperation.handle_upload_file代碼編寫

class FileOperation:
    @staticmethod
    def handle_upload_file(file, filename):
        path = r'./img/'  # 圖片保存路徑
        print(f"filename={filename}")
        if not os.path.exists(path):
            os.makedirs(path)
        with open(path + filename, 'wb') as destination:
            for chunk in file.chunks():
                # print(chunk)
                destination.write(chunk)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM