欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Django接收照片儲存文件的實例代碼

 更新時間:2020年03月07日 09:39:23   作者:PythonNew_Mr.Wang  
這篇文章主要介紹了Django接收照片儲存文件的實例代碼 ,代碼簡單易懂,非常不錯,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

后端:

from rest_framework.views import APIView
from car import settings
from django.shortcuts import render, redirect, HttpResponse
from dal import models
from django.http import JsonResponse
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

class Image(APIView):

  def post(self, request):
    file_obj = request.FILES.get('send',None)

    print("file_obj",file_obj.name)

    file_path = os.path.join(BASE_DIR, 'media', 'user/img', file_obj.name)

    print("file_path", file_path)

    with open(file_path, 'w') as f:
      for chunk in file_obj.chunks():
        f.write(chunk)

    message = {}
    message['code'] = 200

    return JsonResponse(message)

前端ajax:

<form method="post" action="/upload/" enctype="multipart/form-data" target="ifm1">
    <input type="file" name="send"/>

    <input type="submit" value="Form表單提交"/>
  </form>

下面在看下在Django中接收文件并存儲

首先是一個views函數(shù)的例子 

def get_user_profiles(request):
  if request.method == 'POST':
      myFile = request.FILES.get("filename", None)
      if myFile:
        dir = os.path.join(os.path.join(BASE_DIR, 'static'),'profiles')
        destination = open(os.path.join(dir, myFile.name),
                  'wb+')
        for chunk in myFile.chunks():
          destination.write(chunk)
        destination.close()
      return HttpResponse('ok')

這是一個簡單的接收客戶端上傳的頭像文件并保存的例子,應該看過這個就已經(jīng)大體會使用接收文件了

但是這里的filename是客戶端上傳的文件名,也可能是像下面這樣的表單 

<input type="file" name="filename" />

如果不知道固定上傳的文件名,想要客戶端上傳什么文件就以其上傳的名字命名可以這么寫

def get_user_profiles(request):
  if request.method == 'POST':
    if request.FILES:
      myFile =None
      for i in request.FILES:
        myFile = request.FILES[i]
      if myFile:
        dir = os.path.join(os.path.join(BASE_DIR, 'static'),'profiles')
        destination = open(os.path.join(dir, myFile.name),
                  'wb+')
        for chunk in myFile.chunks():
          destination.write(chunk)
        destination.close()
      return HttpResponse('ok')

不過這個是通過輸出request.FILES試出來的,不知道是否有更合適的方法。

總結

到此這篇關于Django接收照片儲存文件的實例代碼 的文章就介紹到這了,更多相關Django儲存文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論