【Python】+Django+Vue+Element UI 實現圖片上傳功能
阿新 • • 發佈:2021-12-22
一、效果
二、前端程式碼
僅修改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)如果忍耐算是堅強 我選擇抵抗 如果妥協算是努力 我選擇爭取